3

我正忙于为安卓设备制作应用程序。现在我正在测试一些东西。

我想在有限的时间内改变背景颜色,比如说5。每次背景改变时,我希望它在2-3秒后再次改变。

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

我希望有我可以使用的教程或示例。

谢谢!

4

2 回答 2

7

在 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);

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

于 2012-06-09T23:30:04.597 回答
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();

         }

   }

}

于 2012-06-09T23:31:04.223 回答