1

タイマーが停止した後にボタンをクリックした後にタイマーを再起動する方法を知りたいです。私が欲しいのは:

  1. 最初のボタンクリック: タイマースタート
  2. 2 回目のクリック: タイマー停止
  3. 3 回目のクリック: タイマーの再起動

最初の 2 つは機能していますが、再起動はしていません。

private Button startButton;

private TextView timerValue;

private long startTime = 0L;

private Handler customHandler = new Handler();

long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;

private int checkState = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pyramide);

    timerValue = (TextView) findViewById(R.id.pyramideTime);

    startButton = (Button) findViewById(R.id.pyramideButton);

    startButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // start
            if (checkState == 0) {
                startButton.setText("Fertig");
                startTime = SystemClock.uptimeMillis();
                customHandler.postDelayed(updateTimerThread, 0);
                checkState = 1;
            }
            // pause
            else if (checkState == 1) {
                startButton.setText("Neu starten");
                timeSwapBuff += timeInMilliseconds;
                customHandler.removeCallbacks(updateTimerThread);
                checkState = 2;
            }
            // restart
            else if (checkState == 2) {
                timerValue.setText("0");
                timeInMilliseconds = 0L;

                customHandler.postDelayed(updateTimerThread, 0);
                checkState = 0;
                startButton.setText("Fertig");
            }
        }
    });

}

private Runnable updateTimerThread = new Runnable() {

    public void run() {

        timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

        updatedTime = timeSwapBuff + timeInMilliseconds;

        int secs = (int) (updatedTime / 1000);
        int mins = secs / 60;
        secs = secs % 60;
        int milliseconds = (int) (updatedTime % 1000);
        timerValue.setText("" + mins + ":" + String.format("%02d", secs)
                + ":" + String.format("%03d", milliseconds));
        customHandler.postDelayed(this, 0);
    }

};
4

1 に答える 1