3

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.

Faisal
  • 1,332
  • 2
  • 13
  • 29
  • Possible duplicate of [Disable back button in android](https://stackoverflow.com/questions/4779954/disable-back-button-in-android) – peco Oct 05 '19 at 20:56

1 Answers1

6

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.

Pavlo Ostasha
  • 14,527
  • 11
  • 35