前言
APP有些页面中,需要点击特定的按钮才能返回到上一页面甚至退出APP,而不是在屏幕中左右滑动返回或者是点击底部设备自带的返回按钮返回。
方法
在代码中重写onBackPressed()
方法,并且在该方法中写我们按下设备返回按钮时需要处理的逻辑,然后调用我们自己的返回按钮和逻辑即可。
/**
* Called when the activity has detected the user's press of the back
* key. The {@link #getOnBackPressedDispatcher() OnBackPressedDispatcher} will be given a
* chance to handle the back button before the default behavior of
* {@link android.app.Activity#onBackPressed()} is invoked.
*
* @see #getOnBackPressedDispatcher()
*/
@SuppressWarnings("deprecation")
@Override
@MainThread
public void onBackPressed() {
mOnBackPressedDispatcher.onBackPressed();
}