Update UI with Thread sleep

夙愿已清 提交于 2019-12-01 00:46:04

I recently learned how to do this. There is a good tutorial here: http://www.vogella.com/articles/AndroidPerformance/article.html#handler

It's a little tricky at first, you're executing on the main thread, you start a sub-thread, and post back to the main thread.

I made this small activity to flash buttons on and off to make sure I know what's going on:

public class HelloAndroidActivity extends Activity {

/** Called when the activity is first created. */



   Button b1;

   Button b2;

   Handler myOffMainThreadHandler;

   boolean showHideButtons = true;


@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);   

    setContentView(R.layout.main);

    myOffMainThreadHandler = new Handler();  // the handler for the main thread


    b1 = (Button) findViewById(R.id.button1);

    b2 = (Button) findViewById(R.id.button2);


}



public void onClickButton1(View v){ 



   Runnable runnableOffMain = new Runnable(){



                @Override

                public void run() {  // this thread is not on the main

                       for(int i = 0; i < 21; i++){

                             goOverThereForAFew();



                             myOffMainThreadHandler.post(new Runnable(){  // this is on the main thread

                                    public void run(){

                                           if(showHideButtons){

                                           b2.setVisibility(View.INVISIBLE);          

                                           b1.setVisibility(View.VISIBLE);

                                           showHideButtons = false;

                                           } else {

                                           b2.setVisibility(View.VISIBLE);          

                                           b1.setVisibility(View.VISIBLE);

                                           showHideButtons = true;

                                           }

                                    }

                             }); 



                       }

                }



   };



   new Thread(runnableOffMain).start();



}



   private void goOverThereForAFew() {

         try {

                Thread.sleep(500);

         } catch (InterruptedException e) {                   

                e.printStackTrace();

         }

   }

}

Use handlers in your UI thread:

Handler mHandler = new Handler();

Runnable codeToRun = new Runnable() {
    @Override
    public void run() {
        LinearLayout llBackground = (LinearLayout) findViewById(R.id.background);
        llBackground.setBackgroundColor(0x847839);
    }
};
mHandler.postDelayed(codeToRun, 3000);

Handlers will run whatever code you'd like, on the UI thread, after a specified amount of time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!