Question

Hi im trying to get a button to flash, I have tried to change the background with a loop, but not having much luck any suggestions thanks

int count = 0;
while (count < 10000) {  // test: boolean test within (..)
    if (count % 2 != 0) { 
        helpt.setBackgroundColor(getResources().getColor(R.color.Blue));
    } 
    else { 
        helpt.setBackgroundColor(getResources().getColor(R.color.Red));
    } 
    count = count + 1;  
}
Était-ce utile?

La solution

This will change the colour every one second:

int count = 0; //Declare as instance variable    
Activity activity; //Declare as instance variable 

//Inside onCreate()
activity = this;
    new Timer().schedule(new TimerTask() {

        @Override
        public void run() {

            activity.runOnUiThread(new Runnable() {
                public void run() {
                    if (count < 10000) {
                        if (count % 2 != 0) {
                            helpt.setBackgroundColor(getResources()
                                    .getColor(android.R.color.black));
                        } else {
                            helpt.setBackgroundColor(getResources()
                                    .getColor(android.R.color.white));
                        }
                        count = count + 1;
                    }
                }
            });

        }
    }, 0, 1000);

Autres conseils

You dont have any form of delay, of course you wouldn't see it flash. It will run through that loop very quickly. Also for standards you should be using a for loop, not a while. For is explicityly for when you know how many times you are going to run.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top