有些专家告诉我为什么这段代码不起作用,目的很简单,在一段时间内改变按钮的颜色,在那段时间之后你必须将颜色返回到原始颜色。问题是不按顺序运行,应该是一个改变颜色的按钮,等待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;
}
}
}
答案 0 :(得分:0)
您可以使用邮件队列:
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;
}
}
};