0

We're trying to show a loading screen, do some expensive operations (represented with the sleep) and after the operation finished display a message.

expected behaviour: STEP 1: the visibility of rl_loading (RelativeLayout) is set to visible STEP 2: application sleeps for 2 seconds STEP 3: message is shown

what actually happens: STEP 2: the application sleeps for 2 seconds STEP 1+3: visibility changes and message is shown at the same time

Could anyone please explain why that happens and what to change to achieve the expected behaviour?

 mainIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_loading.setVisibility(View.VISIBLE); //STEP 1
                try { 
                    Thread.sleep(2000); //STEP 2
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                msg("message"); //STEP 3
            }
        });
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    Your `Thread.sleep(2000)` is locking the main thread. Meaning the visibility set to visible will never be applied, because you're never letting Android continue it's execution of the UI thread. When that 2 seconds is over, you show the message, and finally let the execution of the UI thread continue – Ferdz Jul 04 '19 at 15:24
  • You could use animations for what you want. But as Ferdz said, current code is behaving this way because it runs on the same thread that sends Android UI updates. Simplest fix is you will have to run it on some other thread (via `Handler`, maybe), and use [runOnUiThread](https://stackoverflow.com/questions/11140285/how-do-we-use-runonuithread-in-android). – M. Prokhorov Jul 04 '19 at 15:28

0 Answers0