Search code examples
androidmultithreadingdelaytextview

How to load TextView one after another by using Thread


Here is my onCreate Method

     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // Show the splash screen
        setContentView(R.layout.progressbar);
        initActionbar();




        mytext=(TextView)findViewById(R.id.progresstextview1);
        mytext1 = (TextView)findViewById(R.id.progresstextview2);
        mytext2 = (TextView)findViewById(R.id.progresstextview3);



        Thread t = new Thread();
        Thread t1 = new Thread();
        Thread t2 = new Thread();

        t.start();
        mytext.setVisibility(View.VISIBLE);


        t1.start();
        mytext1.setVisibility(View.VISIBLE);


        t2.start();
        mytext2.setVisibility(View.VISIBLE);
  }

Here is my run method

   @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<1000;i++)
        {

        }
    }

I want my 3 TextView to load one after another with some delay.The problem is the all the three textview is getting loaded very first and the delay is not happening.Another problem is the Main UI thread is starting after few seconds.Any help in this regard will be much appreciated !!!


Solution

  • Great way to do such things is to use android.os.Handler

    See example:

            mytext=(TextView)findViewById(R.id.progresstextview1);
            mytext1 = (TextView)findViewById(R.id.progresstextview2);
            mytext2 = (TextView)findViewById(R.id.progresstextview3);
    
            uiThreadHandler  = new Handler();    
            showDelayed(mytext, 1000);
            showDelayed(mytex1, 2000);
            showDelayed(mytex2, 3000);
      }
    
      public void showDelayed(final View v, int delay){
          uiThreadHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    v.setVisibility(View.Visible);
                }
            }, delay);
      }
    

    Also, keep in mind: Thread creation may be an expensive operation, so try to avoid lines of code like this

    new Thread().start();
    

    Instead - try to use another method, or at least use ThreadPool from Executor's framework