简体   繁体   中英

Handling back press in a fragment using Navigation Control in Android Java

I have this in my fragment

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                AlertDialog.Builder builder= new AlertDialog.Builder(getContext());
                builder.setMessage("Are you sure you want to logout");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // GO BACK
                    }
                });
                builder.setNegativeButton("No", null);
                builder.show();
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    }

Can you show me how to go back to the previous fragment when I click "Yes" in the Alert?

you can back by pop the current fragment from stack

1- If you are using navigation component use this:

NavHostFragment.findNavController(this).popBackStack();

2- If you are not using FragmentManger use this:

getFragmentManager().popBackStack();

If you are not using navigation component I suggest you to use it, it's recommended by google, take a look here to know how to migrate to navigation component click here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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