在第二次迭代中,Android View类线程在循环中停止



这是视图类:

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的位置

为动画目的更新数据的方式非常奇怪。有一种内置的方法可以实现这些目的:postInvalidateDelayed

@Override protected void onDraw(Canvas canvas) {
    //calculate data
    //animate it
    postInvalidateDelayed(1000 / 30);//request drawing 30 frames per second.  
}

最新更新