EyaqubAli
EyaqubAli

Reputation: 101

How to solve onbackpressed deprecated in java on android studio project API level 34

I created a Java project on Android Studio. Android target API level 34 but the problem is onbackpressed deprecated. you can see this problem

   @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

Image

Upvotes: 10

Views: 7667

Answers (3)

brassmookie
brassmookie

Reputation: 417

Adding to one of the answers above, which may be incomplete for some people.

Add the following to your onCreate() method.

OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
   @Override
   public void handleOnBackPressed() {
      // the 3 lines below replace the functionality of super.onBackPressed();
      setEnabled(false);
      getOnBackPressedDispatcher().onBackPressed();
      setEnabled(true);
      // any additional code
   }
};
getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);

Upvotes: 0

Pavan Prajapati
Pavan Prajapati

Reputation: 111

Use this in your onCreate()

OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            // handle backpressed here
        }
    };
    getOnBackPressedDispatcher().addCallback(this,onBackPressedCallback);

Upvotes: 11

HelloThere12345
HelloThere12345

Reputation: 1958

You need to use onBackPressedDispatcher.addCallback(new ...) in your onCreate().

You can test its execution by displaying a toast in the callback for example.

Upvotes: 4

Related Questions