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我可以找到一个解决我的问题的方法,我想与你分享:
SOLUTION:
// 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()
3)在需要重复代码的任何地方使用startRepeatingTask()
4)在任何您想要停止重复的地方使用stopRepeatingTask()
。
干杯! ;)
答案 0 :(得分:1)
您的应用程序是强制关闭的,因为您正在尝试从Timer
创建的线程更新UI元素。只允许主线程更新UI。这可以使用Handler
查看有关如何实施此问题的this答案。