为什么在线程启动之前按钮的背景不会改变?它在线程休眠结束后发生变化。我提到如果没有线程,背景会改变。
answer1Top.setBackgroundDrawable(correct);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//I want to stop this
playerScTop--;
playerScoreTop.setText(String.valueOf(playerScTop));
答案 0 :(得分:2)
创建一个扩展AsyncTask
的新类,将其View
传递给其以更改背景以及两个后台Drawable
实例,然后:
onPreExecute()
(在UI线程上运行),在视图上设置第一个背景可绘制doInBackground()
(在后台线程上运行),睡2秒
onPostExecute()
(在UI线程上运行),在视图上设置另一个drawable 未经测试的示例代码:
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));
}
}
从你的Activity / Fragment / etc中调用(不需要来保持创建的任务在一个字段中):
new BackgroundChangeTask(BackgroundChangeTask, correct, theOtherDrawable).execute();
答案 1 :(得分:2)
answer1Top.setBackgroundDrawable(correct);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
playerScTop--;
playerScoreTop.setText(String.valueOf(playerScTop));
}
}, 2000);