Alex
Alex

Reputation: 1659

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:

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! I would like the Button Text to be changed every 1 second.

Any expert can help?

Thank to Ole I could find out a solution for my problem that I would like to share with you:

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
2)Also, hd = new Handler() in onCreate()
3) Use startRepeatingTask() wherever you desire your repetitive code to be repeated.
4) Use stopRepeatingTask() wherever you desire to stop repeating.

Cheers! ;)

Upvotes: 0

Views: 1427

Answers (1)

Ole
Ole

Reputation: 7979

Your application is force-closing because you are trying to update UI elements from a thread created by the Timer. Only the main thread is allowed to update the UI. This can be solved using a Handler

Have a look at this answer on how to implement this.

Upvotes: 1

Related Questions