2017-05-07 65 views
0

我想要创建从5秒开始的倒数计时器,并按下按钮,当前时间增加3秒。 我用一个处理程序来处理倒数计时器,我知道我们不能使用CountdownTimer。 这里是我的代码:给处理程序添加3秒

Handler handler = new Handler(); 
int delay = 1000; 
r = new Runnable() { 
        @Override 
        public void run() { 

         int timeOut = finalTime - 1; 
         String printedTime = Integer.toString(timeOut); 
         timer.setText(printedTime); 
         handler.postDelayed(this,delay); 
       }; 

我更新,这是简单的方法正确的代码:

timer = (TextView) findViewById(R.id.timer); 
    addSecs = (Button) findViewById(R.id.addSecs); 

    final Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      currentTime = timer.getText().toString(); 
      time = Integer.parseInt(currentTime); 
      time-=1; 
      updateTime = Integer.toString(time); 
      timer.setText(updateTime); 
      handler.postDelayed(this,1000); 
     } 
    },1000); 

    addSecs.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      currentTime = timer.getText().toString(); 
      time = Integer.parseInt(currentTime); 
      time+=3; 
      updateTime = Integer.toString(time); 
      timer.setText(updateTime); 
     } 
    }); 
+0

我假设'timeOut'和'finalTime'以秒为单位?只需在你的按钮onClick(View v)'事件 – Carpetfizz

+0

@Carpetfizz上增加'finalTime + = 3'即可。我错过了onClick。 Thanx aloooooot ... – rexo

回答

0

使用可以根据自己的逻辑计时器

使用CountDownTimer

下面的代码更改

1st param是以毫秒为单位的起始定时器,
第2个参数是count切断区间

new CountDownTimer(5000, 1000) { 
    @Override 
    public void onTick(long millisUntilFinished) { 
     //5 ,4 , 3, 2, 1 
     Log.d(TAG,"starting nuclear in " + (millisUntilFinished/1000)); 
    } 
    @Override 
    public void onFinish() { 
     //finish code 
    } 

}.start(); 

如果你想使用处理器

timeOut = 5; 
private Runnable runnable = new Runnable() { 
    @Override 
    public void run() { 
     /* do what you need to do */ 
     Log.d(TAG,"starting nuclear in " + timeOut--); 
     /* and here comes the "trick" */ 
     if(timeOut > 0) 
      handler.postDelayed(this, 1000); 
    } 
}; 

private Handler handler = new Handler(); 
handler.postDelayed(runnable, 1000);