Search code examples
javaandroidmultithreadingtextviewthread-sleep

When I click on the activity I have 3 Text View in that. I want to load the Text View one after another like after a gap of 2 seconds?


I am not sure but my research led me to come to this point. I think I need to create Thread object and then I can use Thread.sleep(seconds); But I am not sure how it works with Text View.

  private void runThread() {

    new Thread() {
        public void run() {
            int i = 0;
            while (i++ < 2) {
                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            TextView tv1 = (TextView) findViewById(R.id.tvFirst);
                            TextView tv2 = (TextView) findViewById(R.id.tvSecond);
                            TextView tv3 = (TextView) findViewById(R.id.tvThird);
                        }
                    });
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

This is not even responding. I know I am doing wrong here but this is all what I can think of right now. Any help will be appreciated.


Solution

  • Use Handler.postDelayed . Example:

     new Handler().postDelayed(new Runnable(){
        @Override
         public void run(){
             runOnUiThread(new Runnable() {
    
                        @Override
                        public void run() {
                            TextView tv2 = (TextView) findViewById(R.id.tvSecond);
                            tv2.setText("I set this text after waiting for 2 seconds");
    
                        }
                    });
    
          }
     },2000);
    

    This will update your second textView after two seconds. You can do pretty much the same with the others.