Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable back button pressed in android fragment class

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 is my sample code:

public class Login extends Fragment {     public View onCreateView(LayoutInflater inflater, ViewGroup container,        ,Bundle savedInstanceState) {         ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login, null);         return root;     }      public void onBackPressed() {     } } 
like image 226
JellyBean Avatar asked Jul 19 '13 05:07

JellyBean


People also ask

Which piece of code handles the back navigation of the fragments?

Activity onBackPressed() If you are using onBackPressed() to handle Back button events, we recommend using a OnBackPressedCallback instead.


2 Answers

You have to override onBackPressed of parent FragmentActivity class. Therefore, put your codes in parent FragmentActivity. Or you can call parent's method by using this:

public void callParentMethod(){     getActivity().onBackPressed(); } 

in FragmentActivity override onBackPressed Method and not call its super class to disable back button.

@Override public void onBackPressed() {   //super.onBackPressed();   //create a dialog to ask yes no question whether or not the user wants to exit   ... } 
like image 76
Gunhan Avatar answered Sep 21 '22 12:09

Gunhan


Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity:

    // Disable onBack click     requireActivity().onBackPressedDispatcher.addCallback(this) {       // With blank your fragment BackPressed will be disabled.     } 

Here is the android doc link: https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

like image 43
pRaNaY Avatar answered Sep 20 '22 12:09

pRaNaY