倒计时使用handler.postDelayed无法正常工作

时间:2014-04-27 02:55:10

标签: java android

似乎postDelayed没有等待。我在片段中运行它。

// count down
mCounterTextView.setText(Integer.toString(sCountDownFrom));
final Handler handler = new Handler();
for(int i = (sCountDownFrom-1); i >= 0; i--) {
    final int index = i;
    Log.d("ZoneHelp", "countdown: " + Integer.toString(index));
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // do this after the delay
            mCounterTextView.setText(Integer.toString(index));
        }
    }, 1000); // 1 second counter
}

当我运行它时,三个日志(2,1,0)立即打印出来,我没有得到我希望的影响。

1 个答案:

答案 0 :(得分:0)

我用这段代码自己解决了...谢谢你的评论。我意识到发生了什么因为它。这是我的解决方案:

class CountRunnable implements Runnable {
  private final int mCount;

  public CountRunnable(final int count) {
    mCount = count;
  }

  @Override
  public void run() {
    mCounterTextView.setText(Integer.toString(mCount));
  }
}

// count down
mCounterTextView.setText(Integer.toString(sCountDownFrom));
final Handler handler = new Handler();
for(int i = (sCountDownFrom-1), j=0; i >= 0; i--, j++) {
  Log.d("ZoneHelp", "countdown: " + Integer.toString(i));
  handler.postDelayed(new CountRunnable(i), 500+(j*1000)); // 1 second counter
}