Reputation: 101
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();
}
Upvotes: 10
Views: 7667
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
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
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