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

后端 未结 4 634
北恋
北恋 2020-12-23 22:23

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

So how can

相关标签:
4条回答
  • 2020-12-23 22:32

    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
        }
    
    0 讨论(0)
  • 2020-12-23 22:50

    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
    
    0 讨论(0)
  • 2020-12-23 22:55

    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().

    0 讨论(0)
  • 2020-12-23 22:55

    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);
    
    0 讨论(0)
提交回复
热议问题