开发者

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

I tried with threads, but an开发者_StackOverflow中文版droid throws "CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.".

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

--

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


There is an easier way to do it: use 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.

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


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

    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


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


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
    }


You can show your view and then hide it this way.

View view = yourView;
view.setVisibility(View.VISIBLE);
new Handler().postDelayed(() ->  view.setVisibility(View.GONE), 3000);


I got Stuck in Such Kind of Problem. So, I heard about Coroutines. That they can do these kind of tasks without disturbing Main Thread.

lifeCycleScope.launch{ delay(2000) binding.imageView.visibility = View.GONE }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜