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

半腔热情 提交于 2019-12-23 00:32:09

问题


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


回答1:


You don't need to create a handler:

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



回答2:


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.




回答3:


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.




回答4:


Sorry for the wrong interpretation of the question,

Use textView .setVisibility(View.INVISIBLE)

within a handler



来源:https://stackoverflow.com/questions/20165829/android-best-way-to-make-a-view-disappear-after-a-defined-amount-of-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!