CountdownTimer暂停和恢复功能

时间:2012-11-06 08:41:31

标签: android countdown countdowntimer

我根据我在Google搜索的教程创建了一个倒数计时器。但我无法恢复倒计时。当我按下按钮时,它将从10再次重新启动。

我想创建一个能够暂停和恢复的倒数计时器。谢谢!这是我的代码:

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TimerC extends Activity {
Button btns;
    TextView tv;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer_c);

    btns = (Button)findViewById(R.id.btnstartpause);
    tv  = (TextView)findViewById(R.id.tv);
    tv.setText("10"); 
    btns.setText("Start");

    final MyCounter timer = new MyCounter(10000,1000);

  btns.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (btns.getText()== "Start")
            {
                timer.start();  

                btns.setText("Pause");
            }
            else if (btns.getText()== "Pause")
            {
                btns.setText("Start");
                timer.cancel();                 
            }
        }
    });    
}

public class MyCounter extends CountDownTimer{

    public MyCounter(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {
        System.out.println("Timer Completed.");
        tv.setText("Timer Completed.");
    }

    @Override
    public void onTick(long millisUntilFinished) {
        tv.setText((millisUntilFinished/1000)+"");
        System.out.println("Timer  : " + (millisUntilFinished/1000));
    }
  }
}

2 个答案:

答案 0 :(得分:1)

您的问题应该是字符串比较:

 btns.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

        if (btns.getText()== "Start")
        {
            timer.start();  

            btns.setText("Pause");
        }
        else if (btns.getText()== "Pause")
        {
            btns.setText("Start");
            timer.cancel();                 
        }
    }
});  

您应该使用object.equals(otherObject),因为==运算符会比较referances而不是值。例如:

 btns.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

        if (btns.getText().equals("Start"))
        {
            timer.start();  

            btns.setText("Pause");
        }
        else if (btns.getText().equals("Pause"))
        {
            btns.setText("Start");
            timer.cancel();                 
        }
    }
}); 

答案 1 :(得分:1)

millisUntilFinished的{​​{1}}时间值保存在类属性中。当你想重新启动计时器时,用这个值作为第一个参数重新实例化它,如下所示:
编辑:
将计时器设置为类属性:

onTick

将听众改为:

private MyCounter timer;