Navigation
应用导航 · androidx.navigation
NavigationEvent:统一处理导航事件2.10.0-beta01
用 NavigationEventDispatcher 统一接收返回手势、按键等导航事件,并设置处理优先级。
最后更新 2026-08-01
复制即用
import androidx.navigationevent.NavigationEvent
import androidx.navigationevent.NavigationEventDispatcher
import androidx.navigationevent.NavigationEventDispatcher.Companion.PRIORITY_OVERLAY
import androidx.navigationevent.NavigationEventDispatcherOwner
import androidx.navigationevent.NavigationEventHandler
import androidx.navigationevent.NavigationEventInfo
// 自定义事件信息类型(建议 data class 提供结构性相等)
class PageInfo(val title: String) : NavigationEventInfo()
// 自定义 Handler:继承抽象类并重写生命周期方法
class BackHandler(
initialInfo: PageInfo,
) : NavigationEventHandler<PageInfo>(initialInfo, isBackEnabled = true) {
override fun onBackStarted(event: NavigationEvent) {
// 用户开始返回手势,准备 UI
}
override fun onBackProgressed(event: NavigationEvent) {
// 手势进行中,按 event.progress 更新 UI
updateSwipeProgress(event.progress)
}
override fun onBackCompleted() {
// 用户确认返回,执行导航
navigateBack()
}
override fun onBackCancelled() {
// 手势取消,恢复 UI
}
}
// 获取 dispatcher(Compose 场景通过 LocalNavigationEventDispatcherOwner)
val dispatcher = (view.parent as? NavigationEventDispatcherOwner)?.navigationEventDispatcher
// 注册处理器
val handler = BackHandler(PageInfo("详情页"))
dispatcher?.addHandler(handler, PRIORITY_OVERLAY)
// 不再需要时移除(通过 handler 自身的 remove())
handler.remove()常见陷阱
onBackCompleted默认抛异常:任何可能完成的 handler 都必须重写它。- 忘移除 handler:
handler.remove(),否则持续接收事件(dispatcher.removeHandler是 internal)。 - 优先级理解错:
PRIORITY_OVERLAY覆盖层优先于PRIORITY_DEFAULT。 - 事件信息未更新:页面切换后记得
setInfo,否则 UI 展示旧上下文。
要点
NavigationEvent携带swipeEdge(边缘来源)、progress(0..1 进度)、touchX/Y、frameTimeMillis,统一表达手势/按键导航。NavigationEventHandler是抽象类:构造参数为(initialInfo, isBackEnabled, isForwardEnabled),通过重写onBackStarted/onBackProgressed/onBackCompleted/onBackCancelled响应事件。onBackCompleted默认抛异常——任何可能完成的 handler 都必须重写它。dispatcher.addHandler(handler, priority)注册,优先级PRIORITY_DEFAULT与PRIORITY_OVERLAY(覆盖层优先)。- 移除处理器调用
handler.remove()(dispatcher.removeHandler是 internal)。 setInfo(currentInfo, backInfo, forwardInfo)更新导航上下文供 UI 展示。- 该库是较新 API(1.2.0-alpha03),用于统一返回手势、键盘等导航输入;实现细节以当前源码为准。