使用Thread睡眠更新UI

Rem*_*ker 2 multithreading android sleep

我正忙着为Android设备制作应用程序.现在我正在测试一些东西.

我想改变背景颜色限制时间,让我们说5.每次背景改变,我希望它在2-3秒后再次改变.

如果我使用的是Thread类,它会在Thread完成后加载整个模板,你看不到颜色的变化,但它们在"background"中运行(我可以在LogCat中看到).

我希望有一个我可以使用的教程或示例.

谢谢!

Zai*_*ani 5

在UI线程中使用处理程序:

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);
Run Code Online (Sandbox Code Playgroud)

处理程序将在指定的时间后在UI线程上运行您想要的任何代码.


小智 5

我最近学会了如何做到这一点.这里有一个很好的教程:http: //www.vogella.com/articles/AndroidPerformance/article.html#handler

一开始有点棘手,你在主线程上执行,你启动一个子线程,然后回发到主线程.

我做了这个小活动,打开和关闭闪光按钮,以确保我知道发生了什么:

公共类HelloAndroidActivity扩展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();

         }

   }
Run Code Online (Sandbox Code Playgroud)

}