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() { } }
Activity onBackPressed() If you are using onBackPressed() to handle Back button events, we recommend using a OnBackPressedCallback instead.
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 ... }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With