Pierre-Antoine
Pierre-Antoine

Reputation: 8109

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

Upvotes: 1

Views: 3321

Answers (4)

Heinrisch
Heinrisch

Reputation: 5935

You don't need to create a handler:

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

Upvotes: 4

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

Sorry for the wrong interpretation of the question,

Use textView .setVisibility(View.INVISIBLE)

within a handler

Upvotes: 0

Peri Hartman
Peri Hartman

Reputation: 19484

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.

Upvotes: 1

Ricardo
Ricardo

Reputation: 7965

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.

Upvotes: 1

Related Questions