我在 Fragment 中使用 CountDownTimer
并试图在用户点击手机中的物理后退按钮时停止它。我尝试覆盖 onPause
、onDestroy
、onStop
、onDestroyView
但似乎没有任何效果。有点迷失在这里。有人可以在这里给我指点吗?
public class Foo extends Fragment {
CountDownTimer myTimer;
@Override
public void onStop() {
super.onStop();
myTimer.cancel();
}
@Override
public void onPause() {
super.onPause();
myTimer.cancel();
}
@Override
public void onDestroyView() {
super.onDestroyView();
myTimer.cancel();
}
@Override
public void onDestroy() {
super.onDestroy();
myTimer.cancel();
}
@OnClick(R.id.btn_greenleft_no)
public void goBack() {
myTimer.cancel();
Objects.requireNonNull(getActivity()).onBackPressed();
}
@OnClick(R.id.btn_greenright_yes)
public void showSuccess(View view) {
markAll();
myTimer.cancel();
(new MusicPlayer()).playSound(getContext(), "cheers.mp3");
final Snackbar snackbar = Snackbar.make(snackBarView, R.string.congratulations, Snackbar.LENGTH_SHORT);
snackbar.show();
myTimer.cancel();
}
private void startTimer(final View view) {
int Seconds = 5;
myTimer = new CountDownTimer(Seconds * 1000 + 1000, 1000) {
public void onTick(long millisUntilFinished) {
String rem = String.valueOf(millisUntilFinished / 1000);
Log.d("APP_DEBUG", "Timer: " + rem);
}
public void onFinish() {
goBack();
}
}.start();
}
}
最佳答案
这是我的 2 美分。 fragment 没有 onBackPressed() Activity
类中存在的方法。当用户按下物理后退按钮时调用它。这是文档所说的:
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
您可以做的是覆盖 Foo
fragment 的父 Activity 中的 onBackPressed()
方法,然后使用一个接口(interface)与按下后退按钮的 fragment 进行通信由用户。在 fragment 中,您可以使用所需的代码来取消计时器。 This answer在问题How to implement onBackPressed() in Fragments?可以帮助示例代码。
关于android - 在 fragment 中按下物理后退按钮时取消 CountDownTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630812/