Timer会多次添加某个TableRow

时间:2017-02-08 21:09:14

标签: java android runnable

我的应用中有一个基本的计时器

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;
}

1 个答案:

答案 0 :(得分:1)

检查发生了什么的一个好方法是每次Handler运行时记录,每次addHeader触发

e.g:

    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被调用两次。这是因为500msHandlertimerHandler.postDelayed(this, 500);正在运行,检查当前时间和开始时间之间的差异,以分钟和秒为单位(忽略ms)。要解决此问题,请尝试更改

timerHandler.postDelayed(this, 1000);

{{1}}