Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried with threads, but android 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..

like image 995
The Student Avatar asked Jul 14 '10 15:07

The Student


3 Answers

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

like image 109
user890973 Avatar answered Oct 03 '22 21:10

user890973


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
like image 33
Brandon O'Rourke Avatar answered Oct 03 '22 20:10

Brandon O'Rourke


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);
like image 41
mbonnin Avatar answered Oct 03 '22 20:10

mbonnin