[Android] Easily control the event when the Back button is pressed in Fragment

Overview

――When I was creating a certain app, I wanted to put in a process to disable the back button, so a memorandum --For Activity, you can just override OnBackPressed, but for fragment, that's not the case.

MyActivity.java


@Override
    public void onBackPressed() {
      //Insert the processing when the back button is pressed
    }

--You can pass the value via Interface, but it is troublesome to specify the ID and tag. .. .. --I was looking for an easier way, and it seems that it can be implemented only within Fragment by using OnBackPressedDispatcher. (It was the fastest when I looked at the document from the beginning ...)

Method

MyFragment.java


public class MyFragment extends Fragment {
    private OnBackPressedCallback mBackButtonCallback;

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mBackButtonCallback = new OnBackPressedCallback(true) {
            @Override 
            public void handleOnBackPressed() {
                //Insert the processing when the back button is pressed
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, mBackButtonCallback);
    }

    @Override
    public void onDestroy(){
        mBackButtonCallback.remove();
        super.onDestroy();
    }
}

Remarks

――It's very easy, but when implementing this, if you do not explicitly release the callback by remove () with onDestroy etc., the process will be executed in other Fragment etc. ――It doesn't mean that you will release it without permission, so I think you need to be careful about that point.

Recommended Posts

[Android] Easily control the event when the Back button is pressed in Fragment
How to perform a specific process when the back button is pressed in Android Fragment
[swift] How to control the behavior when the back button of NavigationBar is pressed
[Swift] Setting the behavior when the Share button is pressed
Change the processing when the button on RecyclerView is pressed for each list
[Android / Java] Have the host Fragment (caller) call back the event from DialogFragment
When the project is not displayed in eclipse
Behavior when each is executed in the reverse order Range
How to output the value when there is an array in the array
[Android / Java] Understand the description type in listener settings (button installation)
[Android] I want to get the listener from the button in ListView
How to write the view when Vue is introduced in Rails?