android - 当用户打开下一个片段时,如何停止 CountDownTimer 计数?
问题描述
我有一个 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()
推荐阅读
- excel - 从 Excel 管理对 Azure Data Lake 中文件夹的授权
- asp.net - 没有参数的 Http 路由和路由内的一个点
- c# - 使用 RefactorThis.GraphDiff 库
- google-app-engine - 使用 Web API 在 Google App Engine 中创建应用程序失败。错误:409 - 此应用程序已存在且无法重新创建
- python - 在 python 2.7 中使用 comtypes 获取正在运行的 AutoCAD 应用程序
- javascript - 在被 raw-loader 引入之前如何编译一个 javascript 文件?
- jquery - Flexslider 缩略图轮播活动类无法正常工作
- c++ - 如何对成对的向量进行排序
不管字符串 - javascript - 图像中间的画布文本
- git - 从git拉取离子源代码后,无法在本地运行代码