简体   繁体   English

Android:使View在定义的时间后消失的最佳方法

[英]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. 我想让textView在一段确定的时间之后成功更改文本,然后消失。

I am not sure what the best way to proceed is. 我不确定最好的处理方法是什么。

The problem of using Thread.sleep(2000); 使用Thread.sleep(2000); , is that it would obviously make the whole UI thread sleep. ,这显然会使整个UI线程休眠。 Using Thread.sleep(2000); 使用Thread.sleep(2000); inside an AsyncTask seems wrong. 内部AsyncTask似乎是错误的。 In addition, it would lead to problems if the user leave the Activity that needs to be updated by the AsyncTask . 另外,如果用户离开需要由AsyncTask更新的Activity,则将导致问题。

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: 您可以为此使用Runnable

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) 使用textView .setVisibility(View.INVISIBLE)

within a handler 在处理程序内

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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