android - 如何在用户打开下一个 fragment 时停止 CountDownTimer 计数?

标签 android android-progressbar androidx

我有一个 CountDownTimer,当用户来到这个 fragment 时,它开始从 17 秒倒计时到 0。现在应该有两个选项:

  1. 用户在倒计时到 0 之前点击按钮,按钮打开下一个 fragment

  2. 倒计时到 0 auto 打开下一个 fragment

这是我想要的预期结果,但我找不到实现此目标的方法。当用户单击按钮时,如何停止倒计时?我尝试使用 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()

关于android - 如何在用户打开下一个 fragment 时停止 CountDownTimer 计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877738/

相关文章:

安卓 : Progress bar not shown even after setting visible.

java - 如何显示dailymotion云上传的进度条

android x 设计依赖

android - 非法状态异常 : unknown destination during restore

android - 不推荐使用 setTargetFragment() 后如何替换它

android - 为什么 DDMS 会在 android studio 中禁用 ADB 集成

java - 如何在 ubuntu 14.0 中运行演示 "hello world"android 应用程序?

android - android中的等待进度条

android - 即使手机处于 sleep 状态,也会在后台运行上传过程

android - 删除 TextChangedListener 然后重新添加它