faul faul - 1 month ago 9
Android Question

Android: Updating UI with a Button?

So I have some simple code but it seems to not be working.. any suggestions?

I just want an image to show after a button is pressed then become invisible after 2 seconds.

button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
firstImage.setVisibility(ImageView.VISIBLE);
// delay of some sort
firstImage.setVisibility(ImageView.INVISIBLE);
}
}


The image never shows, it always stays invisible, should I be implementing this in another way? I've tried handlers.. but it didn't work, unless I did it wrong.

Answer

Never make your UI thread sleep!

Do this:

final Handler handler = new Handler();

button.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
      firstImage.setVisibility(ImageView.VISIBLE);
      handler.postDelayed(new Runnable(){
            public void run(){
                 firstImage.setVisibility(ImageView.INVISIBLE);
            }
      }, DELAY);
   }
}

Where you would set DELAY as 2000 (ms).