从Android 10版本开始,系统提供了手势导航功能。我们可以在Android设备上从屏幕左侧向右/从屏幕右侧向左滑动手势来实现类似按下Back返回键的功能。从Android 13版本(API Level 33)开始,onBackPressed()方法将被弃用,我们可以使用AndroidX 的API来实现滑动手势功能的回调处理。当你将应用程序更新到SDK33及之后的版本后你将会看到如下提示:
为了让应用实现返回手势回调的处理,我们需要先在build.gradle.kts文件中添加以下依赖:
dependencies {
implementation("androidx.activity:activity-ktx:1.9.0-alpha02")
· · ·
}
在添加了依赖之后我们需要在AndroidManifest.xml清单文件中将"android:enableOnBackInvokedCallback"属性设置为true:
<application
android:enableOnBackInvokedCallback="true"
· · ·
</application>
Kotlin Code:
class MainActivity: AppCompatActivity() {
private lateinit var mBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
// 在Activity中处理返回手势
onBackPressed(true){
// TODO 你可以在这里编写代码逻辑来处理返回手势
val data = "This is data for MainActivity!"
val intent = Intent()
intent.putExtra("mData", data)
setResult(RESULT_OK, intent)
finish()
}
// 在Fragment中处理返回手势
/*requireActivity().onBackPressed {
// Do something
}*/
}
}
fun AppCompatActivity.onBackPressed(isEnabled: Boolean, callback: () -> Unit) {
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(isEnabled) {
override fun handleOnBackPressed() {
callback()
}
})
}
Java Code:
public class SecondActivity extends AppCompatActivity {
ActivitySecondBinding secondBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
secondBinding = ActivitySecondBinding.inflate(getLayoutInflater());
setContentView(secondBinding.getRoot());
onMyBackPressed(true, new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
intent.putExtra("data_return", "Hello FirstActivity");
setResult(RESULT_OK, intent);
finish();
}
});
}
public void onMyBackPressed(Boolean isEnable, final Runnable callback) {
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(isEnable) {
@Override
public void handleOnBackPressed() {
callback.run();
}
});
}
}