繁体   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);

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

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