大家好,首先我是 android studio 的新手。我正在尝试制作倒数计时器,我让它工作了
然后我想改变背景颜色,每一刻,每一秒。
谢谢你!
new CountDownTimer(3000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
String text = String.format(Locale.getDefault(), " %02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
textView.setText(text);
getWindow().getDecorView().setBackgroundColor(Color.RED);
}
@Override
public void onFinish() {
textView.setTextSize(20);
textView.setText("done.");
getWindow().getDecorView().setBackgroundColor(Color.rgb(0, 153, 51));
}
}.start();
问题在于,在每个刻度上,您将背景颜色设置为白色,然后立即设置为红色,在里面onTick
。这很可能会导致用户看不到白色,因为它会在每个刻度上立即被覆盖。您需要一种方法来为每个刻度更改为单一颜色。
不要忘记始终在 UI 线程上运行 UI 相关代码。您可以在此处阅读有关如何操作的更多信息。
如果您想为每个刻度在白色和红色之间交替,那么您可以CountDownTimer
像这样设置一个标志:
new CountDownTimer(10000, 1000) {
private boolean white = true;
@Override
public void onTick(final long millisUntilFinished) {
runOnUiThread(new Runnable() {
@Override
public void run() {
final int color;
if (white) //Select color depending on flag's value:
color = Color.WHITE;
else
color = Color.RED;
white = !white; //Flip the flag.
getWindow().getDecorView().setBackgroundColor(color);
String text = String.format(Locale.getDefault(), " %02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
textView.setText(text);
}
});
}
@Override
public void onFinish() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setTextSize(20);
textView.setText("done.");
getWindow().getDecorView().setBackgroundColor(Color.rgb(0, 153, 51));
}
});
}
}.start();
或者更好的是,您可以依赖millisUntilFinished
作为单个参数给出的值onTick
,如下所示:
final long total = 10000, interval = 1000;
new CountDownTimer(total, interval) {
@Override
public void onTick(final long millisUntilFinished) {
runOnUiThread(new Runnable() {
@Override
public void run() {
final long millisElapsed = total - millisUntilFinished;
final int color;
if ((millisElapsed / interval) % 2 == 0)
color = Color.WHITE;
else
color = Color.RED;
getWindow().getDecorView().setBackgroundColor(color);
String text = String.format(Locale.getDefault(), " %02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
textView.setText(text);
}
});
}
@Override
public void onFinish() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setTextSize(20);
textView.setText("done.");
getWindow().getDecorView().setBackgroundColor(Color.rgb(0, 153, 51));
}
});
}
}.start();
这种方法应该更好,因为如果我从的文档中CountDownTimer
正确理解,似乎millisUntilFinished
(在 中给出的onTick
)不能保证是间隔的倍数,这也取决于该onTick
方法正在执行的工作量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句