这是视图类:
public class Ball extends View implements Runnable {
public Ball(Context context) {
super(context);
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(500, 200);
//setY(100);
this.setLayoutParams(lp);
Log.d("test", "Ball created");
Thread t = new Thread(this);
t.start();
}
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
float y = getY();
Log.d("test", "first y: " + y);
Log.d("test", "LINE --- LINE");
y = y + 30;
Log.d("test", "setting y: " + y);
setY(y);
Log.d("test", "before sleep");
Thread.currentThread().sleep(1000);
Log.d("test", "after sleep");
}
}
catch(Throwable e)
{
Log.d("error", e.getMessage());
}
}
@Override
protected void onDraw(Canvas canvas) {
Log.d("test", "onDraw called");
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#FF0000"));
canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), paint);
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(0 + radius, 0 + radius, radius, paint);
Log.d("test", "onDraw Ended");
}
}
在run方法中,在循环内部,如果我将其更改为:
y = y;
甚至:
y = 30; //or any other number
线程继续工作,但如果代码是:
y = y + 30; // or any other number
然后在执行setY(y)后的第二次迭代中(我不知道为什么确实是2次迭代),它停止并且没有抛出任何错误,我无法理解这个原因,任何人都可以找到一些关于这可能是什么原因的线索吗?
我只想让球每秒改变y位置
答案 0 :(得分:0)
为动画目的更新数据是一种非常奇怪的方式。为此目的有内置方法:postInvalidateDelayed
。
@Override protected void onDraw(Canvas canvas) {
//calculate data
//animate it
postInvalidateDelayed(1000 / 30);//request drawing 30 frames per second.
}