java - 用计时器改变圆圈的颜色

标签 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);
    }
}

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

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

提前致谢!

最佳答案

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

//-------------------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------------------------

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

感谢大家!

关于java - 用计时器改变圆圈的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32538611/

相关文章:

c# - 从计时器线程调用 GUI 线程上的方法

multithreading - Delphi应用程序中的定期任务

Android:在用户界面中显示的计时器

Java Stream 从对象列表生成映射

java - 是否可以在 Amazon S3 上压缩目录,而不是下载 -> zip -> 上传

android - Workmanager(定期)获取位置和上传数据(Asynctask)被杀死

android - 如何使用抽屉导航正确替换 fragment

java - Wicket 路径样式参数

java - 在 Java 中,我可以放置所有常量的文件类型是什么?

android - Android 中的 FBConnect 窗口泄露?