創建延伸AsyncTask
一個新的類,它傳遞View
其改變背景以及兩個後臺Drawable
實例,則:
在
onPreExecute()
(上UI線程運行)
- ,設置第一背景上繪製的視圖
- 在
doInBackground()
(運行在後臺線程),睡眠2秒
- 在
onPostExecute()
(運行Ò ñUI線程),設置其它可繪製你的看法
未經測試示例代碼:
public class BackgroundChangeTask extends AsyncTask<Void, Void, Void> {
private View view;
private Drawable background1;
private Drawable background2;
public BackgroundChangeTask(View view, Drawable background1, Drawable background2) {
this.view = view;
this.background1 = background1;
this.background2 = background2;
}
@Override
protected void onPreExecute() {
view.setBackgroundDrawable(background1);
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// too bad
}
return null;
}
@Override
protected void onPostExecute(Void result) {
view.setBackgroundDrawable(background2);
// add anything else you want to run "after 2 seconds" here, e.g.
playerScTop--;
playerScoreTop.setText(String.valueOf(playerScTop));
}
}
調用從活動/片段/等這樣的(無需保持創建的任務各地在現場):
new BackgroundChangeTask(BackgroundChangeTask, correct, theOtherDrawable).execute();
不要'睡眠()'在UI線程,不更新關閉UI線程UI組件。你想達到什麼目的? –
我想設置一個背景2秒,然後我想設置另一個背景,線程睡眠時間過後 – Alex