我是 Android 新手。我的程序模拟交通灯的操作,并根据经过的秒数显示适当的颜色。通过点击buttonRandom
,从0到6秒显示绿色背景,从6到7秒显示黄色背景,从7到9秒显示红色背景。
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonRed:
mTextView.setText(R.string.buttonRed);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorRed));
break;
case R.id.buttonYellow:
mTextView.setText(R.string.buttonYellow);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorYellow));
break;
case R.id.buttonRandom:
int count = 0;
while (count <= 10) {
Date date = new Date();
int sec = date.getSeconds();
if (sec % 10 >= 0 && sec % 10 < 6) {
mTextView.setText(R.string.buttonGreen);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorGreen));
count++;
}
else if (sec % 10 >= 6 && sec % 10 < 7) {
mTextView.setText(R.string.buttonYellow);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorYellow));
count++;
}
else if (sec % 10 >= 7 && sec % 10 < 9) {
mTextView.setText(R.string.buttonRed);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorRed));
count++;
}
}
}
但是,这段代码不会自行更改背景,需要每次按下按钮。如何确保按一次背景自动改变?
最佳答案
However, this code does not change the background on their own, it is necessary each time to press the button.
那是因为你的 while 循环运行得太快了,不到一秒就已经完成了 10 次循环。您想在此处使用处理程序或其他东西每秒进行检查
int sec = 0;
case R.id.buttonRandom:
final Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
if (sec % 10 >= 0 && sec % 10 < 6) {
mTextView.setText(R.string.buttonGreen);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorGreen));
} else if (sec % 10 >= 6 && sec % 10 < 7) {
mTextView.setText(R.string.buttonYellow);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorYellow));
} else if (sec % 10 >= 7 && sec % 10 < 9) {
mTextView.setText(R.string.buttonRed);
mRelativeLayout.setBackgroundColor(getResources().getColor(R.color.colorRed));
}
sec++;
if (sec < 11) {
h.postDelayed(this);
}
}
}, 1000);
关于java - 循环不会自动运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38180016/