ComponentActivity的OnBackPressedD

2019-11-11  本文已影响0人  王玮123

主题

分享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)

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

image.png
方法
  1. addCallback(OnBackPressedCallback onBackPressedCallback)

Add a new OnBackPressedCallback.

image.png
  1. addCallback(LifecycleOwner owner, OnBackPressedCallback onBackPressedCallback)

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

image.png

有几种情况:

  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.

优缺点

优点:

缺点:

如何用

image.png image.png

我们项目中如何用

image.png image.png

相关知识链接

上一篇下一篇

猜你喜欢

热点阅读