简体   繁体   中英

Android: best way to make a View disappear after a defined amount of time

I would like to make a textView disappear after a define amount of time succeeding a change of the text.

I am not sure what the best way to proceed is.

The problem of using Thread.sleep(2000); , is that it would obviously make the whole UI thread sleep. Using Thread.sleep(2000); inside an AsyncTask seems wrong. In addition, it would lead to problems if the user leave the Activity that needs to be updated by the AsyncTask .

There must be a cleaner way to implement that. If you know any: feel free to answer :-)

You don't need to create a handler:

view.postDelayed(new Runnable(){
  @Override
  public void run()
  {
    view.setVisibility(View.GONE);
  }
}, 10000);

You can use a Runnable for this:

Handler myHandler = new Handler();
Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        //Hide your view
    }
};

Then after your change of text, add the following:

myHandler.postDelayed(myRunnable, TIME_IN_MILLISECONDS);

Hope it helps.

Can you do something like this?

In your activity, create a handler:

Handler handler = new Handler()
{
  @Override
  public void handleMessage (Message msg)
  {
    if (msg.what == HIDE_VIEW)
      hideView();  // defined elsewhere in your activitry
  }
}

And at the point where you want to start the timer, do this:

postDelayed (new Runnable()
{
  @Override
  public void run()
  {
    Message msg = handler.obtainMessage();
    msg.what = HIDE_VIEW;
    msg.obj = null;
    handler.sendMessage (msg);
  }
}, 10000);

Not sure if you need this level of asynchronousity.

Sorry for the wrong interpretation of the question,

Use textView .setVisibility(View.INVISIBLE)

within a handler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM