![](/img/trans.png)
[英]In Android, how do I change the color of a button, pause for a few seconds, then change it again?
[英]I want to change the color of a button for a few seconds than change it back
我的Android按鈕顏色為藍色。 我想將按鈕顏色更改為紅色5秒鍾。 5秒后,我需要將按鈕顏色改回藍色。
這是我的代碼
new Handler().postDelayed(new Runnable() {
public void run() {
eyesOnchkBtn.setBackgroundColor(Color.RED);
}
}, 5000);
eyesOnchkBtn.setBackgroundColor(Color.BLUE); // It wont change the color button as normal
希望以下代碼有所幫助
eyesOnchkBtn.setBackgroundColor(Color.RED);
new CountDownTimer(5000, 50) {
@Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void onFinish() {
eyesOnchkBtn.setBackgroundColor(Color.BLUE);
}
}.start();
只需稍微改變你的代碼,
eyesOnchkBtn.setOnClickListener( new OnClickListener(){
@Override
public void onClick() {
// set the color red first.
eyesOnchkBtn.setBackgroundColor(Color.RED);
// change to original after 5 secs.
new Handler().postDelayed(new Runnable() {
public void run() {
eyesOnchkBtn.setBackgroundColor(Color.BLUE);
}
}, 5000);
}
});
試試這個
Timer myTimer;
MyTimerTask myTask = new MyTimerTask();
myTimer = new Timer();
myTimer.schedule(myTask, 0, 3000);
class MyTimerTask extends TimerTask {
public void run() {
try {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
//Your color change code here
} catch (Exception e) {
e.printStackTrace();
}
}
}
//完成工作后停止計時器。
@Override
public void onPause() {
super.onPause();
try {
myTimer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onStop() {
super.onStop();
try {
myTimer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
button.setBackgroundColor(Color.GREEN);
button.postDelayed(new Runnable() {
@Override
public void run() {
button.setBackgroundColor(Color.BLUE);
}
}, 5000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.