使用计时器时应用程序停止

时间:2016-05-10 05:37:10

标签: java android android-studio timer

我试图使用onDraw方法在屏幕上随机绘制两个矩形,我想清除屏幕并每2秒制作两个新的矩形。所以我在Timer中包含了invalidate()。但是,当我运行此代码时,它首先显示两个矩形,并在2秒后停止运行。我猜我的Timer有问题,因为我的代码在添加Timer之前运行良好。 为什么这不起作用,我应该如何修复它以便每2秒绘制2个矩形(删除之前的矩形)? 提前谢谢。

protected void onDraw(Canvas canvas){
    super.onDraw(canvas);   
    int width = canvas.getWidth();
    int height = canvas.getHeight();
    int rectangleWidth = width / 5;//Width of a rectangle
    int rectangleHeight = height / 15; //height of a rectangle
    for(int i = 0; i< 2; i++) {
        randomLeft = randomGenerator1.nextInt(width - rectangleWidth);
        colors = new String[]{"red", "black", "blue", "green", "yellow"};
        int randomColorIndex = randomGenerator2.nextInt(colors.length);
        randomColor = new Paint();
        randomColor.setColor(Color.parseColor(colors[randomColorIndex]));
        randomColor.setStyle(Paint.Style.FILL);
        Rectangle newRectangle = new Rectangle(rectangleWidth, rectangleHeight);
        newRectangle.setColor(randomColor);
        rectangles.add(newRectangle);
        redRect.set(randomLeft, y, randomLeft + rectangleWidth, y + rectangleHeight);
        rects.add(redRect);
        canvas.drawRect(redRect, randomColor);
    }
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            invalidate();
        }
    }, 2000);
}

0 个答案:

没有答案