自定义视图动画

时间:2014-04-01 22:11:49

标签: android animation view

在我的 Android 应用程序中,我有一个自定义的View对象,我在这样的布局中引用它:

<view
    class="com.usmaan.game.MenuBall"
    android:layout_width="30dp"
    android:layout_height="30dp"/>

该课程如下:

public class MenuBall extends View {

public MenuBall(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint();
    paint.setColor(Color.LTGRAY);
    canvas.drawCircle(getMeasuredWidth() * 0.5f, getMeasuredHeight() * 0.5f, getMeasuredHeight() * 0.5f, paint);
}
}

球/圆圈在屏幕上绘制得非常精细。

然而,我想要做的是为球设置动画,使其垂直和/或水平移动。知道如何实现这个目标吗?

2 个答案:

答案 0 :(得分:1)

也许您可以在活动中实例化您的视图并像其他视图一样设置动画,您可以看到:http://developer.android.com/guide/topics/graphics/view-animation.html以获取更多参考资料

答案 1 :(得分:1)

这个睡眠应该在一个线程中完成,以免锁定ui,但会让你知道一种方法。有几种方法可以做到这一点,实际上只取决于您希望它与用户/应用程序事件相关的内容。

 float x= getMeasuredWidth() * 0.5f;
 float destinationX= getMeasuredWidth() * 0.8f;
 boolean isRunning=true;
 Paint paint = new Paint();
 paint.setColor(Color.LTGRAY);

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

 while (isRunning) {
            Thread.sleep(200); // Waits for .2 second (200 milliseconds)
            if(x<destinationX){
                x+=5;} 
            else {isRunning=false;}
            canvas.drawCircle(x,y, getMeasuredHeight() * 0.5f, paint);
            invalidate();
 }
}