Search code examples
androidandroid-navigation-editor

How to show warning message when back button is pressed in fragments


I want application to show warning message when user press back button and if user select Yes it will go back. And i am in navigation graph fragment.

I have searched many time in stack Overflow and tried:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Save Or Not");
    builder.setMessage("Do you want to save this? ");
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            /*Go back:-I dont know how*/
        }
    });
    builder.setNegativeButton("Discard",null);
    builder.show();
}

But it is showing giver error: Method does not override method from its superclass

Edit: I want to set onBackPressedListener(Mobiles back button) in Navigation graphs fragment


Solution

  • When using Fragments 1.1.0 (which is in alpha right now), you can follow the Provide custom back navigation documentation, which shows how to register an OnBackPressedCallback, which allows you to register for onBackPressed() callbacks from within a Fragment:

    public class MyFragment extends Fragment {
    
      @Override
      public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // This callback will only be called when MyFragment is at least Started.
        OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
            @Override
            public void handleOnBackPressed() {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    
                builder.setTitle("Save Or Not");
                builder.setMessage("Do you want to save this? ");
                builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Save your content
                    save();
                    // Then pop
                    NavHostFragment.findNavController(MyFragment.this).popBackStack();
                }
                builder.setNegativeButton("Discard",null);
                builder.show();
            });
            }
        });
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
      }
    }