Search code examples
androidandroid-jetpack-navigation

Disabling back button in AndroidX Fragment


I'm using Single-Activity pattern(Fragments for each UI) for App development together with Android's Jetpack navigation. Each fragment represent a UI. Is there any simple way to disable back press action(soft/hardware button)?

Thanks.


Solution

  • Try something like

    class MyFragment : Fragment() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            // This callback will only be called when MyFragment is at least Started.
            val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
                // Handle the back button event
            }
    
            // The callback can be enabled or disabled here or in the lambda
        }
        ...
    }
    

    Or to be more verbose and to have more control over your code:

    public class FormEntryFragment extends Fragment {
         @Override
         public void onAttach(@NonNull Context context) {
             super.onAttach(context);
             OnBackPressedCallback callback = new OnBackPressedCallback(
                 true // default to enabled
             ) {
                 @Override
                 public void handleOnBackPressed() {
                     // Handle the back button event
                     // Leave empty do disable back press.
                 }
             };
             requireActivity().getOnBackPressedDispatcher().addCallback(
                 this, // LifecycleOwner
                 callback);
         }
     }
    

    You can read more in the documentation here and here - I took the examples from there

    Hope it helps.