ComponentActivity的OnBackPressedDispatcher

主题

分享ComponentActivity增加了 OnBackPressedDispatcher 来帮助我们在 Fragment 中更好的处理返回事件。

起源

ComponentActivity的OnBackPressedDispatcher_第1张图片
image.png
ComponentActivity的OnBackPressedDispatcher_第2张图片
image.png
ComponentActivity的OnBackPressedDispatcher_第3张图片
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)

Create a new OnBackPressedDispatcher that dispatches System back button pressed events to one or more OnBackPressedCallback instances.
(王玮翻译: 创建一个新的OnBackPressedDispatcher,它将系统后退按钮按下的事件分派给一个或多个OnBackPressedCallback实例。)

ComponentActivity的OnBackPressedDispatcher_第4张图片
image.png
方法
  1. addCallback(OnBackPressedCallback onBackPressedCallback)

Add a new OnBackPressedCallback.

ComponentActivity的OnBackPressedDispatcher_第5张图片
image.png
  1. addCallback(LifecycleOwner owner, OnBackPressedCallback onBackPressedCallback)

Receive callbacks to a new OnBackPressedCallback when the given LifecycleOwner is at least started.

ComponentActivity的OnBackPressedDispatcher_第6张图片
image.png

有几种情况:

  • 如果都调用addCallback(this) ,根据reverse顺序来,后添加的先调用
  • 如果都调用addCallback() ,根据reverse顺序来,后添加的先调用
  • 如果一个调用addCallback(this)一个调用addCallback() ,先调用有生命周期的
  1. hasEnabledCallbacks()

Checks if there is at least one enabled callback registered with this dispatcher.

  1. onBackPressed()

Trigger a call to the currently added callbacks in reverse order in which they were added.

优缺点

优点:

  • 可以在Fragment里处理包括Activity在内的所有返回键操作(配合navigation用很爽)

缺点:

  • 不能在里面调用Activity的onBackPressed()(会产生循环),当Fragment不需要处理返回操作时不能向上传递到Activity

如何用

ComponentActivity的OnBackPressedDispatcher_第7张图片
image.png
ComponentActivity的OnBackPressedDispatcher_第8张图片
image.png

我们项目中如何用

ComponentActivity的OnBackPressedDispatcher_第9张图片
image.png
ComponentActivity的OnBackPressedDispatcher_第10张图片
image.png

相关知识链接

  • https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher
  • https://developer.android.com/jetpack/androidx/releases/activity
  • https://www.youtube.com/watch?v=RS1IACnZLy4&list=PLWz5rJ2EKKc_xXXubDti2eRnIKU0p7wHd&index=6&t=0s
  • https://juejin.im/post/5dbb969f518825213802f3ce

你可能感兴趣的:(ComponentActivity的OnBackPressedDispatcher)