2015-09-12 41 views
2

我只是想用計時器改變我畫的圓的顏色。我已經實現下面的代碼到我的「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); 
    } 
} 

當我運行此,顏色停留在它的默認。

有誰知道我是否必須使用一個處理程序或不同的計時器模型?

提前致謝!

+0

您將問題的標題更改爲「已解決」,請將其更改回原來的位置,並在解決問題的答案旁邊打鉤。 (如果這是你自己的答案,這沒有關係) – Frakcool

+0

好的,謝謝,我會的! – Jolle

+0

謝謝!所有你需要做的就是接受你的答案,你完成了C:(我想你必須等待1或2個小時左右,所以我不記得了)如果我把「t.start();」放入「 – Frakcool

回答

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

這工作很細,我可以用它來做更多的計時器和不同的方法!

謝謝大家!

0

您的t.start()缺失,無論是onCreate,onStart或onResume,這取決於您想要啓動計時器的時間。

+0

」直接在「t.scheduleAtFixedRate(... 1000,1000);」之後會發生錯誤 - >方法start()對於類型Timer < - 未定義嗎? - 我必須添加一個TimerTask嗎? – Jolle