简体   繁体   English

onBackPressed() 在片段中不起作用

[英]onBackPressed() is not working in Fragment

I want to completely it goes to the home of the phone when i back, but onBackPressed() is not working.当我回来时,我想完全将它转到手机的主页,但是onBackPressed()不工作。 My Page is a fragment btw.我的页面是一个片段 btw。

Use getActivity().onBackPressed();使用getActivity().onBackPressed(); in your fragment it will execute onBackPressed() of your parent activity在您的片段中,它将执行您父活动的onBackPressed()

to be more accurate更准确

Activity activity = getActivity();
    if (activity != null) {
        activity.onBackPressed();}

edit: use requireActivity() for avoiding nullpointer编辑:使用requireActivity()来避免空指针

requireActivity().onBackPressed();

onBackPressed callback is handled by your parent activity. onBackPressed 回调由您的父活动处理。 So you can override callback on parent activity所以你可以覆盖父活动的回调

XyzActivity.java: XyzActivity.java:

@Override
public void onBackPressed() {
    handleBackPress();
}


public void handleBackPress() {
    Fragment visibleFragment = getSupportFragmentManager().findFragmentById(R.id.fragmentFrameLayout);
    if (visibleFragment == null) {
        return;
    }else if (visibleFragment instanceof PreviewFragment) {
        CommonFunctions.showDialogActionable(this, "Confirm", "Are you sure you want to exit?",
            "Yes", (dialogInterface, i) -> {
                finish();
            }, "No", null, "", null, true);
        return;
    }else
        finish();
    super.onBackPressed();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM