Нужно Android Studio CountDownTimer, чтобы остановить l oop до вызова onFini sh - PullRequest
0 голосов
/ 16 марта 2020

Итак, я хочу, чтобы l oop остановился, пока таймер не закончит обратный отсчет, чтобы перейти к следующему раунду. Пример: я вызываю часы в начале в основном и таймер запускается на 30 секунд. Моя программа ждет, пока эти 30 секунд не закончатся, пока не перейдет к следующей строке и не вызовет runWorkout ().

Однако, когда я запускаю этот код, происходит следующее: l oop завершает работу и создает много таймеров обратного отсчета. сразу.

package com.example.workoutgenerator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;


public class MainActivityTwo extends AppCompatActivity {

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

    public void runWorkout(int workoutLength) {
        for (int round = 0; round <= workoutLength; round++) {
            // update clock
            setClock(round);
        }
    }

    public void setClock(int currentRound) {
        // clock comes here then we go back to the clock
        int sixty = 60;
        int thirty = 30;
        int ten = 10;

        if (currentRound == 0 || currentRound == 3 || currentRound == 6 || currentRound == 9 || currentRound == 12 || currentRound == 15)
        { clock(sixty); }
        if (currentRound == 1 || currentRound == 4 || currentRound == 7 || currentRound == 10 || currentRound == 13 || currentRound == 16)
        { clock(thirty); }
        else
        { clock(ten); }
    }

    public void clock(int time) {
        final TextView clock = findViewById(R.id.clock);
        new CountDownTimer(time*1000, 1000) {
            public void onTick(long millisLeft) {
                clock.setText(String.valueOf(millisLeft/1000));
            }
            public void onFinish() {
                return;
            }
        }.start();
    }

    public void main() {
        clock(30);
        int workoutLength = 18;
        runWorkout(workoutLength);
    }
}
...