0

This is a curiosity question but is there a way to delay the final line in an if statement.

eg:

if(m_Toolbar.getVisibility() == View.VISBILE) {
               ...........
    m_Toolbar.setVisibility(View.GONE);
}

How would you go about delaying the final line like (ie.GONE)?

Rylan Howard
  • 53
  • 11
EquiWare
  • 127
  • 2
  • 12
  • What do you mean with delay? Usually ``Thread.sleep`` will cause a delay but I'm sure that's not what you want here. – f1sh Jan 18 '18 at 16:41

4 Answers4

4

Please DO NOT use Thread.Sleep() that will freeze the UI Use a Handler

Handler h = new Handler();
h.postDelayed(new Runnable() {
            @Override
            public void run() {

            }
        },delayMilliseconds);
tyczj
  • 69,495
  • 52
  • 182
  • 280
2

Thread.sleep will cause UI to freeze , I suggest to use Handler instead

if(m_Toolbar.getVisibility() == View.VISBILE) {
    ...........
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            m_Toolbar.setVisibility(View.GONE);
        }
    }, 3000);//3 seconds
}
Ali Faris
  • 15,922
  • 10
  • 37
  • 64
0

You can use the following TimeUnit.SECONDS.sleep(1); which waits for one second.

Maltanis
  • 494
  • 5
  • 13
0

best is :

 if(m_Toolbar.getVisibility() == View.VISBILE) {
    ...........
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            m_Toolbar.setVisibility(View.GONE);
        }
    }, 5000);//5 seconds
}

But if you need multiply actions you can use this:

      if(m_Toolbar.getVisibility() == View.VISBILE) {

                    int Delay = 5;  //set Your request delay

                    new Thread(new Runnable(){
                        public void run() {
                              // TODO Auto-generated method stub

                             do{
                                  try {

                                      runOnUiThread(new Runnable() {
                                          public void run() {

                                              Delay --;

                                              if( Delay == 0){

                                                  m_Toolbar.setVisibility(View.GONE);
                                              }else if( Delay == 1){
                                                    //another action

                                               }

                                          }
                                      });   

                                      Thread.sleep(1000);


                                  } catch (InterruptedException e) {
                                      //TODO Auto-generated catch block
                                      e.printStackTrace();
                                  } 

                              }while(Delay > 0);

                           }
                      }).start();



    }
Ferhad Konar
  • 404
  • 1
  • 7
  • 9