我的应用程序中有一个基本的计时器:
TextView timerTextView = (TextView) findViewById(R.id.timer);
long startTime = 0;
Handler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000) * 1;
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%02d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
if (minutes == 45 && seconds == 0) {
addHeader("2nd Half");
}
}
};
addHeader()方法:
private void addHeader(String header) {
TableLayout table = (TableLayout) findViewById(R.id.myTable);
TableRow tr = new TableRow(this);
tr.setLayoutParams(...);
TextView textView = new TextView(this);
textView.setLayoutParams(..);
textView.setText(header);
// more code
tr.addView(textView);
table.addView(tr);
}
onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTimer();
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
当我的计时器到达45:00时,新行将多次添加到TableLayout中。我创建了一个替代解决方案,但我想知道自己所缺少的。
if (!isAdded) {
addHeader("2nd Half");
isAdded = true;
}
最佳答案
检查正在发生的事情的一种好方法是在每次运行Handler
和每次addHeader
触发时进行记录
例如:
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000) * 1;
int minutes = seconds / 60;
seconds = seconds % 60;
millis = millis % 1000;
timerTextView.setText(String.format("%02d:%02d", minutes, seconds));
Log.d("MainActivity", String.format(Locale.ENGLISH,"Checking time: %02d:%02d:%03d" , minutes, seconds, millis));
timerHandler.postDelayed(this, 500);
if (minutes == 45 && seconds == 0) {
Log.d("MainActivity", String.format(Locale.ENGLISH,"2nd Half: %02d:%02d:%03d" , minutes, seconds, millis));
addHeader("2nd Half");
}
}
这样做您会看到
addHeader
被调用了两次。这是因为500ms
的每个Handler
都在运行,以分钟和秒(忽略ms)为单位检查当前时间和开始时间之间的时差。要解决此问题,请尝试更改timerHandler.postDelayed(this, 500);
至
timerHandler.postDelayed(this, 1000);