Android 如何显示一个视图 3 秒,然后隐藏它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3247554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:18:09  来源:igfitidea点击:

How to show a view for 3 seconds, and then hide it?

androiduser-interface

提问by Tom Brito

I tried with threads, but android throws "CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.".

我尝试使用线程,但 android 抛出“CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。”。

So how can I wait 3 seconds and then hide the view, letting the GUI responsive?

那么我怎样才能等待 3 秒然后隐藏视图,让 GUI 响应呢?

--

——

A Timer uses another thread either, so it will not solve..

定时器也使用另一个线程,所以它不会解决..

采纳答案by Brandon O'Rourke

Spawn a separate thread that sleeps for 3 seconds then call runOnUiThreadto hide the view.

生成一个单独的线程,该线程休眠 3 秒,然后调用runOnUiThread以隐藏视图。

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Do some stuff
                }
            });
        }
    };
    thread.start(); //start the thread

回答by user890973

There is an easier way to do it: use View.postDelayed(runnable, delay)

有一种更简单的方法:使用View.postDelayed(runnable, delay)

View view = yourView;
view.postDelayed(new Runnable() {
        public void run() {
            view.setVisibility(View.GONE);
        }
    }, 3000);

It's not very precise: may be hidden in 3.5 or 3.2 seconds, because it posts into the ui thread's message queue.

它不是很精确:可能会在 3.5 或 3.2 秒后隐藏,因为它会发布到 ui 线程的消息队列中。

Use post() or runOnUiThread() just something as setTimeout().

使用 post() 或 runOnUiThread() 就像 setTimeout() 一样。

回答by mbonnin

Without the need to have a reference to a view or sleep a thread:

无需引用视图或休眠线程:

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            // do stuff
        }
    }, 3000);

回答by Gudin

I know this is a stretch, but here's an answer with coroutines if you happen to use them:

我知道这是一个延伸,但是如果您碰巧使用协程,这里有一个答案:

    lifecycleScope.launch {
        delay(3000)
        header.visibility = View.GONE
    }