简体   繁体   English

每隔一段时间更改按钮中的文本颜色

[英]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);

in Logcat: 在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

which means that btn1.setTextColor(...) is executing only once ! 这意味着btn1.setTextColor(...)仅执行一次 I would like the Button Text to be changed every 1 second . 我希望按钮文本1秒钟更改一次。

Any expert can help? 有专家可以帮忙吗?

Thank to Ole I could find out a solution for my problem that I would like to share with you: 感谢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)Do not forget to declare Handler hd 1)不要忘记声明Handler hd
2)Also, hd = new Handler() in onCreate() 2)此外, hd = new Handler() onCreate() hd = new Handler() onCreate()
3) Use startRepeatingTask() wherever you desire your repetitive code to be repeated. 3)在您希望重复代码重复的地方使用startRepeatingTask()
4) Use stopRepeatingTask() wherever you desire to stop repeating. 4)在您希望停止重复的地方使用stopRepeatingTask()

Cheers! 干杯! ;) ;)

Your application is force-closing because you are trying to update UI elements from a thread created by the Timer . 您的应用程序正在强制关闭,因为您试图从Timer创建的线程中更新UI元素。 Only the main thread is allowed to update the UI. 仅允许主线程更新UI。 This can be solved using a Handler 这可以使用Handler解决

Have a look at this answer on how to implement this. 看看这个答案就如何落实这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM