我有一个CountDownTimer,当用户使用此片段时,它将从17秒开始递减计数到0。现在应该有两个选择:
用户在倒数计数为0之前单击一个按钮,然后该按钮打开下一个片段
倒数计数到0并自动打开下一个片段
这是我想要的理想结果,但我找不到实现此目标的方法。当用户单击按钮时,如何停止倒数计时?我尝试使用progressBar.setVisibility(View.GONE);
,但倒数仍在倒数。任何帮助深表感谢!
这是我的代码:
public View onCreateView (@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
...
// Opens the next fragment after clicking on the Ok button
btnOkFrag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopCountdownTimer();
((GameActivity)getActivity()).setViewPager(2);
}
});
return view;
}
// Countdown 17 seconds
int i = 0;
private void startCountdownTimer() {
progressBar.setProgress(i);
final int totalMsecs = 17 * 1000; // 17 seconds in milli seconds
int callInterval = 100;
/** CountDownTimer */
new CountDownTimer(totalMsecs, callInterval) {
public void onTick(long millisUntilFinished) {
int secondsRemaining = (int) millisUntilFinished / 1000;
float fraction = millisUntilFinished / (float) totalMsecs;
// progress bar is based on scale of 1 to 10.000;
progressBar.setProgress((int) (fraction * 10000));
}
public void onFinish() {
stopCountdownTimer();
((GameActivity)getActivity()).setViewPager(2);
// TODO: 2019-10-18 Open next fragment when the countdown is finished. If user clicks ok button before finish, stop countdown.
}
}.start();
}
private void stopCountdownTimer(){
progressBar.setVisibility(View.GONE);
}
最佳答案
您可以将CountDownTimer(如Ikazuchi在评论中所述)分配给以下变量:
CountDownTimer countDown = new CountDownTimer(totalMsecs, callInterval) {...
然后在分配给按钮的onClick方法中,您可以调用
countDown.cancel()