我正忙于为android设备开发一个应用程序。现在我正在测试一些东西。
我想要改变背景颜色的次数是有限的,比如说5次。每次背景改变,我希望它在2-3秒后再次改变。
如果我使用Thread类,它在线程完成后加载整个模板,你看不到颜色的变化,但它们是在“背景”中运行的(我可以在LogCat中看到)。
我希望有一个我可以使用的教程或例子。
谢谢!
发布于 2012-06-10 07:31:04
我最近学会了如何做到这一点。这里有一个很好的教程: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-10 07:30:05
在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线程上运行您想要的任何代码。
https://stackoverflow.com/questions/10965291
复制相似问题