![](/img/trans.png)
[英]Java Android, how to dynamically change a TextView background color for certain time
[英]Android - change color of a button for a certain time
有专家告诉我为什么此代码不起作用,目的是在一定时间段内更改按钮的颜色很简单,在这段时间之后,您必须将颜色恢复为原始颜色。 问题是不能按顺序运行,应该是一个按钮来更改颜色,等待1s,回到原始颜色,然后对下一个按钮相同,以完成顺序。
对不起,我的英语不好,谢谢。
int temp[] = new int[game.getLevel()];
Handler handler = new Handler();
temp = game.getSequence();
for(int i = 0; i < game.getLevel(); i++)
{
switch (temp[i])
{
case RED:
handler.postDelayed(new Runnable() {
public void run() {
redButton.setBackgroundColor(Color.rgb(255, 0, 0));
}
}, 1000);
redButton.setBackgroundColor(Color.rgb(109, 0, 0));
break;
case GREEN:
handler.postDelayed(new Runnable() {
public void run() {
greenButton.setBackgroundColor(Color.rgb(0, 255, 0));
}
}, 1000);
greenButton.setBackgroundColor(Color.rgb(0, 109, 0));
break;
case YELLOW:
handler.postDelayed(new Runnable() {
public void run() {
yellowButton.setBackgroundColor(Color.rgb(255, 255, 0));
}
}, 1000);
yellowButton.setBackgroundColor(Color.rgb(109, 109, 0));
break;
case BLUE:
handler.postDelayed(new Runnable() {
public void run() {
blueButton.setBackgroundColor(Color.rgb(0, 0, 255));
}
}, 1000);
blueButton.setBackgroundColor(Color.rgb(0, 0, 255));
break;
default:
break;
}
}
}
您可以使用消息队列:
static final int RED = 0;
static final int GREEN = 1;
static final int YELLOW = 2;
static final int BLUE = 3;
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.sendEmptyMessageDelayed(RED, 1000);
}
});
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case RED:
mButton.setBackgroundColor(Color.rgb(255, 0, 0));
mHandler.sendEmptyMessageDelayed(GREEN, 1000);
break;
case GREEN:
mButton.setBackgroundColor(Color.rgb(0, 255, 0));
mHandler.sendEmptyMessageDelayed(YELLOW, 1000);
break;
case YELLOW:
mButton.setBackgroundColor(Color.rgb(255, 255, 0));
mHandler.sendEmptyMessageDelayed(BLUE, 1000);
break;
case BLUE:
mButton.setBackgroundColor(Color.rgb(0, 0, 255));
mHandler.sendEmptyMessageDelayed(RED, 1000);
break;
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.