【问题标题】:Changing Color of Circle with Timer用定时器改变圆圈的颜色
【发布时间】:2015-09-12 12:09:29
【问题描述】:

我只是想用计时器改变我绘制的圆圈的颜色。我在“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);
    }
}

当我运行它时,颜色保持默认值。

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

提前致谢!

【问题讨论】:

  • 您已将问题的标题更改为“已解决”,请将其改回并点击解决您问题的答案旁边的勾号。 (如果是你自己的答案没关系)
  • 谢谢!您所要做的就是接受您的答案,然后您就完成了 C:(我想您必须等待 1 或 2 个小时左右,我不记得了)

标签: java android timer colors


【解决方案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------------------------

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

谢谢大家!

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 如果我输入“t.start();”直接在“t.scheduleAtFixedRate(....1000,1000);”之后出现错误提示 --> 方法 start() 未定义 Timer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多