How to disable back button pressed in android fragment class

后端 未结 9 1177
别跟我提以往
别跟我提以往 2020-12-11 14:39

I want to disable the back button in a fragment class. onBackPressed() doesn\'t seem to work in this fragment. How could I disable the back button?

This

9条回答
  •  心在旅途
    2020-12-11 15:08

    OnBackPressedCallback

    Here is the code which you can write in your Fragment class to customize the back button press.

    public class MyFragment extends Fragment{
    
        @Override
        public void onCreate(Bundle savedInstanceState){
    
            super.onCreate(savedInstanceState);
    
            OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
                @Override
                public void handleOnBackPressed() {
                    // Handle the back button even
                    Log.d("BACKBUTTON", "Back button clicks");
                }
            };
    
            requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    
         }
    
    }
    

    Relevant link

    You can read and research more on this HERE

提交回复
热议问题