Timer多次添加某个TableRow

Timer adds a certain TableRow multiple times

我的应用程序中有一个基本的 Timer

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 是 运行ning,检查当前时间和开始时间之间的差异,以分钟和秒为单位(忽略 ms)。要解决此问题,请尝试更改

timerHandler.postDelayed(this, 500);

timerHandler.postDelayed(this, 1000);