开发者

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 pr开发者_如何转开发essed 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.


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


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);
    }
});


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);
        }
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜