@Override
@MainThread
@CallSuper
@Deprecated
public void onBackPressed() {
getOnBackPressedDispatcher().onBackPressed();
}
Activity中的onBackPressed方法在覆盖时,会提示已经废弃,下面是用新的方案替代
1、在manifest.xml中,设置enableOnBackInvokedCallback为true
<application
android:enableOnBackInvokedCallback="true">
2、在Activity的onCreate方法添加以下代码,在handleOnBackPressed中实现对back的控制
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getOnBackPressedDispatcher().addCallback(this, new androidx.activity.OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
finish();
}
});
}
3、在DialogFragment中,针对android 13及以上需要特殊设置OnBackInvokedDispatcher
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
Window window = dialog.getWindow();
if (window != null && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
// Get the dispatcher
OnBackInvokedDispatcher dispatcher = window.getOnBackInvokedDispatcher();
// Add a callback
dispatcher.registerOnBackInvokedCallback(
OnBackInvokedDispatcher.PRIORITY_DEFAULT,
new OnBackInvokedCallback() {
@Override
public void onBackInvoked() {
// Handle the back button press here
// You can dismiss the dialog or do other things
backPressed();
}
}
);
}
dialog.setOnKeyListener((dialog1, keyCode, event) -> event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK && backPressed());
return dialog;
}