Handling back button in Android Navigation Component

前端 未结 23 1377
遥遥无期
遥遥无期 2020-11-29 18:20

I\'d like to know how properly handle system back button action using Navigation Controller. In my app I have two fragments (for ex. fragment1 and fragment2) and I have an a

23条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 19:11

    If you use Navigation Component follow the codes below in your onCreateView() method (in this example I want just to close my app by this fragment)

     OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
                        .setIcon(R.drawable.icon_01)
                        .setTitle(getResources().getString(R.string.close_app_title))
                        .setMessage(getResources().getString(R.string.close_app_message))
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                getActivity().finish();
                            }
                        })
                        .setNegativeButton(R.string.no, null)
                        .show();
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, backPressedCallback);
    

提交回复
热议问题