ComponentActivity的OnBackPressedD
主题
分享ComponentActivity增加了 OnBackPressedDispatcher 来帮助我们在 Fragment 中更好的处理返回事件。
起源
image.png image.png image.png官方解释
Dispatcher that can be used to register onBackPressedCallback instances for handling the ComponentActivity.onBackPressed() callback via composition.
(王玮翻译: 调度器可以用来注册onBackPressedCallback的引用去处理onbackPressed()的回调通过组合)
API
构造器
OnBackPressedDispatcher()/OnBackPressedDispatcher(Runnable fallbackOnBackPressed)
image.pngCreate a new OnBackPressedDispatcher that dispatches System back button pressed events to one or more OnBackPressedCallback instances.
(王玮翻译: 创建一个新的OnBackPressedDispatcher,它将系统后退按钮按下的事件分派给一个或多个OnBackPressedCallback实例。)
方法
- addCallback(OnBackPressedCallback onBackPressedCallback)
image.pngAdd a new OnBackPressedCallback.
- addCallback(LifecycleOwner owner, OnBackPressedCallback onBackPressedCallback)
image.pngReceive callbacks to a new OnBackPressedCallback when the given LifecycleOwner is at least started.
有几种情况:
- 如果都调用addCallback(this) ,根据reverse顺序来,后添加的先调用
- 如果都调用addCallback() ,根据reverse顺序来,后添加的先调用
- 如果一个调用addCallback(this)一个调用addCallback() ,先调用有生命周期的
- hasEnabledCallbacks()
Checks if there is at least one enabled callback registered with this dispatcher.
- onBackPressed()
Trigger a call to the currently added callbacks in reverse order in which they were added.
优缺点
优点:
- 可以在Fragment里处理包括Activity在内的所有返回键操作(配合navigation用很爽)
缺点:
- 不能在里面调用Activity的onBackPressed()(会产生循环),当Fragment不需要处理返回操作时不能向上传递到Activity