在片段中通过物理返回按钮取消CountDownTimer

9

我在Fragment中使用了一个CountDownTimer,并尝试在用户按下手机的物理返回按钮时停止它。我已经尝试覆盖onPauseonDestroyonStoponDestroyView方法,但似乎都没有起作用。有没有人可以给我指点一下?

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();

    }

}
6个回答

7
这是我的两分意见。Fragment没有onBackPressed()方法,而该方法存在于Activity类中。当用户按下物理返回按钮时,该方法将被调用。以下是文档中的说明:

当活动检测到用户按下后退键时调用。默认实现只是完成当前活动,但您可以重写此操作以执行任何您想要的操作。

您可以在您的Foo片段的父活动中重写onBackPressed()方法,然后使用接口通知片段用户按下了返回按钮。在片段内,您可以编写所需代码以取消计时器。此答案中的示例代码可帮助回答如何在片段中实现onBackPressed()问题。

3
尝试在您的Fragment的父Activity中修改onBackPressed函数。
@Override
public void onBackPressed() {

    // I assume this is the way how You add fragment to fragment manager
    //getSupportFragmentManager().beginTransaction().replace(android.R.id.content, Foo.getInstance(), Foo.TAG).commit()

    // Find fragment by its string TAG and when You get it, call to stop countDownTimer
    Foo foo = (Foo) getSupportFragmentManager().findFragmentByTag(Foo.TAG);
    if (foo != null) {
        foo.stopCountDownTimer();
    }

    super.onBackPressed();
}

下一步是在您的Foo片段中声明两件事情:
public static final String TAG = "Foo";

并且

public void stopCountDownTimer() {
    myTimer.cancel();
}

3

对于片段,您不能使用 onBackPressed 方法,而是请使用以下代码

 @Override
public void onResume() {
    super.onResume();
    if (getView() == null) {
        return;
    }
    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                myTimer.cancel();
                return false;
            }
            return true;
        }
    });
}

3
你还需要调用countDownTime.finish()。我使用过它,对我有效。
@Override
public void onDetach()
{
    super.onDetach();

    if (countDownTimer != null)
    {
        countDownTimer.cancel();
        countDownTimer.onFinish();
    }
}

0

你尝试过使用 onBackPressed() 吗?

 @Override
    public void onBackPressed() {
            super.onBackPressed();
            myTimer.cancel();
            myTimer =null;
    }

上次我检查时,Fragments没有覆盖onBackPressed方法。 - Fawzan

0
你尝试在片段中添加一个OnKeyListener,像这样: 这里的“view”是你片段的父布局,也就是托管计时器的那个。
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.i(tag, "keyCode: " + keyCode);
            if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
               myTimer.cancel();
                return true;
            } 
            return false;
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接