用定时器改变圆的颜色

时间:2015-09-12 12:09:29

标签: java android timer colors

我只想用计时器改变绘制圆圈的颜色。我已将以下代码实施到我的" onCreate"方法:

     Timer t = new Timer();
     t.scheduleAtFixedRate(new TimerTask() {

         @Override
         public void run() { 
             runOnUiThread(new Runnable() {

                 @Override
                 public void run() {
                     Drawing.switchColor();
                 }
             });
         }
     },
     1000,
     1000);

方法switchColor()执行以下操作:

    public static void switchColor() {
    Random r = new Random(30);
    int random = r.nextInt();
    if(random < 10) {
        p.setColor(Color.GREEN);
    }
    else if(random >10 && random < 20) {
        p.setColor(Color.BLUE);
    }
    else {
        p.setColor(Color.RED);
    }
}

当我运行时,颜色保持默认状态。

是否有人知道我是否必须使用其中的处理程序或不同的计时器模型?

提前致谢!

2 个答案:

答案 0 :(得分:1)

我现在找到了合适的解决方案:

//-------------------Part 1 of AddCircleTimer------------------------
     //Declare the timerAddCircle
     timerAddCircle = new Timer();
     timerAddCircle.schedule(new TimerTask() {
         @Override
         public void run() {
             TimerMethodAddCircle();
         }
     }, 1000, 1000);

 //-------------------Part 2 of AddCircleTimer------------------------
private void TimerMethodAddCircle()
{
    //This method is called directly by the timer and runs in the same thread as the timer.
    //We call the method that will work with the UI through the runOnUiThread method.
    this.runOnUiThread(Timer_Add);
}

private Runnable Timer_Add = new Runnable() {
    public void run() {
    //This method runs in the same thread as the UI.               
    //Do something to the UI thread here
         Drawing.addCircle();
         d.invalidate();
    }
};
//-------------------END Part 2 of AddCircleTimer------------------------

这非常好用,我可以将它用于更多的计时器和不同的方法!

感谢所有人!

答案 1 :(得分:0)

您的t.start()在onCreate,onStart或onResume中丢失,具体取决于您何时要启动计时器。