Oliver Oliver - 12 days ago 8
Android Question

Display a Shuffle of button text and backgrounds

I have a button in xml. On button press I wish to rapidly change the background and Text on that button.

I normally would use a code like this for the final result:

String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}

{Button btn = (Button) findViewById(R.id.button1);
btn.setText(String.valueOf(rnd));
btn.setTextColor(Color.parseColor("#000000"));}


Before that is called though I would like perhaps a second or two of a "shuffling" effect.

I have tried using java.util.timer like this:

@Override
public void onClick(View v) {

new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {

String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}

{Button btn = (Button) findViewById(R.id.button1);
btn.setText(String.valueOf(rnd));
btn.setTextColor(Color.parseColor("#000000"));}

}}}, 100 );


Then making a few of these with different backgrounds to fire one after the other. I just can't seem to get the hang of it.

I may need a whole new method to do what I want to do, but I am not sure what the best wat to accomplish what I need is.

rnk rnk
Answer

You should use Handler and make sure that the code that you want to run is in the runnable method :-)

Try something like this from your Activity

Handler handler = new Handler();
....

@Override
public void onClick(View v) {
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
        // set your button color here, no need to use runOnUiThread()
        // as this run() method is executed on Main thread
        }
    }, 100);
}