[英]Change text color in button every interval of time
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
// TODO Auto-generated method stub
Log.i("first iteration","first iteration");
btn1.setTextColor(Color.rgb((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255)));
Log.i("iterating","iteratinggggggggg");
}
}, 0, 1000);
在Logcat中:
01-07 02:39:09.789: I/first iteration(16568): first iteration
01-07 02:39:09.789: I/iterating(16568): iteratinggggggggg
01-07 02:39:10.781: I/first iteration(16568): first iteration
這意味着btn1.setTextColor(...)
僅執行一次 ! 我希望按鈕文本每1秒鍾更改一次。
有專家可以幫忙嗎?
感謝Ole,我可以找到我想與您分享的解決方案:
解:
// UPDATING BTN TEXT DYNAMICALLY
Runnable myRunnableUpdater = new Runnable()
{
public void run() {
colorGenerator();
hd.postDelayed(myRunnableUpdater, 1000);
}
};
void startRepeatingTask()
{
myRunnableUpdater.run();
}
void stopRepeatingTask()
{
hd.removeCallbacks(myRunnableUpdater);
}
private void colorGenerator() {
btn1.setTextColor(Color.rgb((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255)));
}
//END OF UPDATING BTN TEXT DYNAMICALLY!!
1)不要忘記聲明Handler hd
2)此外, hd = new Handler()
onCreate()
hd = new Handler()
onCreate()
3)在您希望重復代碼重復的地方使用startRepeatingTask()
。
4)在您希望停止重復的地方使用stopRepeatingTask()
。
干杯! ;)
您的應用程序正在強制關閉,因為您試圖從Timer
創建的線程中更新UI元素。 僅允許主線程更新UI。 這可以使用Handler
解決
看看這個答案就如何落實這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.