Android: Updating UI with a Button?

2019-06-09 14:41发布

问题:

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.

回答1:

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



回答2:

Well, you will need to add a delay between the two lines. Use a thread or a timer to do this.

Start a thread on click of a button. In the run method, change the ImageView's visibility to VISIBLE, then put the thread to sleep for n secs, and then change then make it invisible.

To call the imageView's setvisibility method, you will need a hanlder here.

Handler handler = new Handler();
handler.post(new Runnable() {
    public void run() {
           image.setVisibiliy(VISIBLE);
           Thread.sleep(200);
           image.setVisibility(INVISIBLE);
    }
});


回答3:

I know this question has already been answered, but I thought I would add an answer for people who like me, stumbled across this looking for a similar result where the delay was caused by a process rather than a "sleep"

button.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
      firstImage.setVisibility(ImageView.VISIBLE);

      // Run the operation on a new thread
      new Thread(new Runnable(){
            public void run(){
                 myMethod();
                 returnVisibility();
            }
      }).start();
   }
}

private void myMethod() {
    // Perform the operation you wish to do before restoring visibility
}

private void returnVisibility() {
    // Restore visibility to the object being run on the main UI thread.
    MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            firstImage.setVisibility(ImageView.INVISIBLE);
        }
    });
}