文档管理中心
您当前浏览的HarmonyOS 5.0.2(API 14)文档归档不再维护,推荐您使用最新版本。详细请参考文档维护策略变更
API参考应用框架ArkUI(方舟UI框架)ArkTS组件导航与切换Navigation

Navigation

本文导读
展开章节

Navigation组件是路由导航的根视图容器,一般作为Page页面的根容器使用,其内部默认包含了标题栏、内容区和工具栏,其中内容区默认首页显示导航内容(Navigation的子组件)或非首页显示(NavDestination的子组件),首页和非首页通过路由进行切换。

说明
  • 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。

  • 该组件从API Version 11开始默认支持安全区避让特性(默认值为:expandSafeArea([SafeAreaType.SYSTEM, SafeAreaType.KEYBOARD, SafeAreaType.CUTOUT], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])),开发者可以重写该属性覆盖默认行为,API Version 11之前的版本需配合expandSafeArea属性实现安全区避让。

  • NavBar嵌套使用Navigation时,内层Navigation的生命周期不和外层Navigation以及全模态的生命周期进行联动。

  • Navigation未设置主副标题并且没有返回键时,不显示标题栏。

子组件

可以包含子组件。

从API Version 9开始,推荐与NavRouter组件搭配使用。

从API Version 10开始,推荐使用NavPathStack配合navDestination属性进行页面路由。

接口

Navigation()

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

Navigation(pathInfos: NavPathStack)

绑定路由栈到Navigation组件。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
pathInfos NavPathStack 路由栈信息。

属性

除支持通用属性外,还支持以下属性:

title

title(value: ResourceStr | CustomBuilder | NavigationCommonTitle | NavigationCustomTitle, options?: NavigationTitleOptions)

设置页面标题。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value ResourceStr10+ | CustomBuilder | NavigationCommonTitle9+ | NavigationCustomTitle9+ 页面标题,使用NavigationCustomTitle类型设置height高度时,titleMode属性不会生效。字符串超长时,如果不设置副标题,先缩小再换行(2行)最后截断。如果设置副标题,先缩小最后截断。
options NavigationTitleOptions11+ 标题栏选项。

subTitle(deprecated)

subTitle(value: string)

设置页面副标题。

从API Version 9开始废弃,建议使用title代替。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value string 页面副标题。

menus(value: Array<NavigationMenuItem> | CustomBuilder)

说明

不支持通过SymbolGlyphModifier对象的fontSize属性修改图标大小、effectStrategy属性修改动效、symbolEffect属性修改动效类型。

设置页面右上角菜单。不设置时不显示菜单项。使用Array<NavigationMenuItem> 写法时,竖屏最多支持显示3个图标,横屏最多支持显示5个图标,多余的图标会被放入自动生成的更多图标。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value Array<NavigationMenuItem> | CustomBuilder 页面右上角菜单。

titleMode

titleMode(value: NavigationTitleMode)

设置页面标题栏显示模式。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value NavigationTitleMode

页面标题栏显示模式。

默认值:NavigationTitleMode.Free

toolBar(deprecated)

toolBar(value: object | CustomBuilder)

设置工具栏内容。不设置时不显示工具栏。items均分底部工具栏,在每个均分内容区布局文本和图标,文本超长时,逐级缩小,缩小之后换行,最后截断。

从API version 10开始,该接口不再维护,推荐使用toolbarConfiguration代替。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value object | CustomBuilder 工具栏内容。

object类型说明:

展开
名称 类型 必填 说明
value string 工具栏单个选项的显示文本。
icon string 工具栏单个选项的图标资源路径。
action () => void 当前选项被选中的事件回调。

toolbarConfiguration10+

toolbarConfiguration(value: Array<ToolbarItem> | CustomBuilder, options?: NavigationToolbarOptions)

说明

不支持通过SymbolGlyphModifier对象的fontSize属性修改图标大小、effectStrategy属性修改动效、symbolEffect属性修改动效类型。

设置工具栏内容。不设置时不显示工具栏。

卡片能力: 从API version 10开始,该接口支持在ArkTS卡片中使用。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value Array<ToolbarItem> | CustomBuilder

工具栏内容,使用Array<ToolbarItem>写法设置的工具栏有如下特性:

工具栏所有选项均分底部工具栏,在每个均分内容区布局文本和图标。

文本超长时,若工具栏选项个数小于5个,优先拓展选项的宽度,最大宽度与屏幕等宽,其次逐级缩小,缩小之后换行,最后截断。

竖屏最多支持显示5个图标,多余的图标会被放入自动生成的更多图标。横屏时,如果为Split模式,仍按照竖屏规则显示,如果为Stack模式需配合menus属性的Array<NavigationMenuItem>使用,底部工具栏会自动隐藏,同时底部工具栏所有选项移动至页面右上角菜单。

使用CustomBuilder写法为用户自定义工具栏选项,除均分底部工具栏外不具备以上功能。

options NavigationToolbarOptions11+ 工具栏选项。

hideToolBar

hideToolBar(value: boolean)

设置是否隐藏工具栏。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value boolean

是否隐藏工具栏。

默认值:false

true: 隐藏工具栏。

false: 显示工具栏。

hideToolBar13+

hideToolBar(hide: boolean, animated: boolean)

设置是否隐藏工具栏,设置是否使用动画显隐工具栏。

元服务API: 从API version 13开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
hide boolean

是否隐藏工具栏。

默认值:false

true: 隐藏工具栏。

false: 显示工具栏。

animated boolean

设置是否使用动画显隐工具栏。

默认值:false

true: 使用动画显示隐藏工具栏。

false: 不使用动画显示隐藏工具栏。

hideTitleBar

hideTitleBar(value: boolean)

设置是否隐藏标题栏。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value boolean

是否隐藏标题栏。

默认值:false

true: 隐藏标题栏。

false: 显示标题栏。

hideTitleBar13+

hideTitleBar(hide: boolean, animated: boolean)

设置是否隐藏标题栏,设置是否使用动画显隐标题栏。

元服务API: 从API version 13开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
hide boolean

是否隐藏标题栏。

默认值:false

true: 隐藏标题栏。

false: 显示标题栏。

animated boolean

设置是否使用动画显隐标题栏。

默认值:false

true: 使用动画显示隐藏标题栏。

false: 不使用动画显示隐藏标题栏。

hideBackButton

hideBackButton(value: boolean)

设置是否隐藏标题栏中的返回键。返回键仅针对titleMode为NavigationTitleMode.Mini时才生效。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value boolean

是否隐藏标题栏中的返回键。

默认值:false

true: 隐藏返回键。

false: 显示返回键。

navBarWidth(value: Length)

设置导航栏宽度。仅在Navigation组件分栏时生效。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value Length

导航栏宽度。

默认值:240

单位:vp

undefined:行为不做处理,导航栏宽度与默认值保持一致。

navBarPosition(value: NavBarPosition)

设置导航栏位置。仅在Navigation组件分栏时生效。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value NavBarPosition

导航栏位置。

默认值:NavBarPosition.Start

mode9+

mode(value: NavigationMode)

设置导航栏的显示模式,支持单栏(Stack)、分栏(Split)和自适应(Auto)。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value NavigationMode

导航栏的显示模式。

默认值:NavigationMode.Auto

自适应:基于组件宽度自适应单栏和双栏。

backButtonIcon9+

backButtonIcon(value: string | PixelMap | Resource | SymbolGlyphModifier)

说明

不支持通过SymbolGlyphModifier对象的fontSize属性修改图标大小、effectStrategy属性修改动效、symbolEffect属性修改动效类型。

设置标题栏中返回键图标。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value string | PixelMap | Resource | SymbolGlyphModifier12+ 标题栏中返回键图标。

hideNavBar9+

hideNavBar(value: boolean)

设置是否隐藏导航栏。设置为true时,隐藏Navigation的导航栏,包括标题栏、内容区和工具栏。如果此时路由栈中存在NavDestination页面,则直接显示栈顶NavDestination页面,反之显示空白。

从API Version 9开始到API Version 10仅在双栏模式下生效。从API Version 11开始在单栏、双栏与自适应模式均生效。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value boolean

是否隐藏导航栏。

默认值:false

navDestination(builder: (name: string, param: unknown) => void)

创建NavDestination组件。使用builder函数,基于name和param构造NavDestination组件。builder下只能有一个根节点。builder中允许在NavDestination组件外包含一层自定义组件, 但自定义组件不允许设置属性和事件,否则仅显示空白。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
builder (name: string, param: unknown) => void 创建NavDestination组件。name:NavDestination页面名称。param:NavDestination页面详细参数。

navBarWidthRange(value: [Dimension, Dimension])

设置导航栏最小和最大宽度(双栏模式下生效)。

规则: 优先级规则详见说明。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value [Dimension, Dimension]

导航栏最小和最大宽度。

默认值:最小默认值 240,最大默认值为组件宽度的40% ,且不大于 432,如果只设置一个值,则未设置的值按照默认值计算。

单位:vp

minContentWidth10+

minContentWidth(value: Dimension)

设置导航栏内容区最小宽度(双栏模式下生效)。

规则: 优先级规则详见说明。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value Dimension

导航栏内容区最小宽度。

默认值:360

单位:vp

undefined:行为不做处理,导航栏内容区最小宽度与默认值保持一致。

Auto模式断点计算:默认600vp,minNavBarWidth(240vp) + minContentWidth (360vp)

说明
  1. 仅设置navBarWidth,不支持Navigation分割线拖拽。

  2. navBarWidthRange指定分割线可以拖拽范围。如果不设置值,则按照默认值处理。拖拽范围需要满足navBarWidthRange设置的范围和minContentWidth限制。

  3. Navigation显示范围缩小:a. 缩小内容区大小。如果不设置minContentWidth属性,则可以缩小内容区至0, 否则最小缩小至minContentWidth。b. 缩小导航栏大小,缩小时需要满足导航栏宽度大于navBarRange的下限。c. 对显示内容进行裁切。

ignoreLayoutSafeArea12+

ignoreLayoutSafeArea(types?: Array<LayoutSafeAreaType>, edges?: Array<LayoutSafeAreaEdge>)

控制组件的布局,使其扩展到非安全区域

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
types Array <LayoutSafeAreaType>

配置扩展安全区域的类型。

默认值:

[LayoutSafeAreaType.SYSTEM]

edges Array <LayoutSafeAreaEdge>

配置扩展安全区域的方向。

默认值:

[LayoutSafeAreaEdge.TOP, LayoutSafeAreaEdge.BOTTOM]。

说明

组件设置LayoutSafeArea之后生效的条件为:

设置LayoutSafeAreaType.SYSTEM时,组件的边界与非安全区域重合时组件能够延伸到非安全区域下。例如:设备顶部状态栏高度100,组件在屏幕中纵向方位的绝对偏移需要在0到100之间。

若组件延伸到非安全区域内,此时在非安全区域里触发的事件(例如:点击事件)等可能会被系统拦截,优先响应状态栏等系统组件。

systemBarStyle12+

systemBarStyle(style: Optional<SystemBarStyle>)

当Navigation中显示Navigation首页时,设置对应系统状态栏的样式。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
style Optional<SystemBarStyle> 系统状态栏样式。
说明
  1. 不建议混合使用systemBarStyle属性和window设置状态栏样式的相关接口,例如:setWindowSystemBarProperties
  2. 初次设置Navigation/NavDestination的systemBarStyle属性时,会备份当前状态栏样式用于后续的恢复场景。
  3. Navigation总是以首页(页面栈内没有NavDestination时)或者栈顶NavDestination设置的状态栏样式为准。
  4. Navigation首页或者任何栈顶NavDestination页面,如果设置了有效的systemBarStyle,则会使用设置的样式,反之如果之前已经备份了样式,则使用备份的样式,否则不做任何处理。
  5. Split模式下的Navigation,如果内容区没有NavDestination,则遵从Navigation首页的设置,反之则遵从栈顶NavDestination的设置。
  6. 仅支持在主窗口的主页面中使用systemBarStyle设置状态栏样式。
  7. 仅当Navigation占满整个页面时,设置的样式才会生效,当Navigation没有占满整个页面时,如果有备份的样式,则恢复备份的样式。
  8. 当页面设置不同样式时,在页面转场开始时生效。
  9. 非全屏窗口下,Navigation/NavDestination设置的状态栏不生效。

recoverable14+

recoverable(recoverable: Optional<boolean>)

配置Navigation是否可恢复。如配置为可恢复,当应用进程异常退出并重新冷启动时,可自动创建该Navigation,并恢复至异常退出时的页面栈。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
recoverable Optional<boolean>

Navigation是否可恢复,默认为不可恢复。

默认值:false

true:页面栈可恢复。

false:页面栈不可恢复。

说明
  1. 使用该接口需要先设置Navigation的id属性,否则该接口无效。
  2. 该接口需要配合NavDestination的recoverable接口使用。
  3. 恢复的过程中不可序列化的信息,例如不可序列化的参数与用户设置的onPop等,会被丢弃,无法恢复。

enableDragBar14+

enableDragBar(isEnabled: Optional<boolean>)

控制分栏场景下是否显示拖拽条。

元服务API: 从API version 14开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
isEnabled Optional<boolean>

是否开启拖拽条,默认为无拖拽条样式。

默认值:false

true:有拖拽条样式。

false:无拖拽条样式。

事件

onTitleModeChange

onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void)

titleMode为NavigationTitleMode.Free时,随着可滚动组件的滑动标题栏模式发生变化时触发此回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
titleMode NavigationTitleMode 标题模式。

onNavBarStateChange9+

onNavBarStateChange(callback: (isVisible: boolean) => void)

导航栏显示状态切换时触发该回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
isVisible boolean isVisible为true时表示显示,为false时表示隐藏。

onNavigationModeChange11+

onNavigationModeChange(callback: (mode: NavigationMode) => void)

当Navigation首次显示或者单双栏状态发生变化时触发该回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
mode NavigationMode

NavigationMode.Split: 当前Navigation显示为双栏;

NavigationMode.Stack: 当前Navigation显示为单栏。

customNavContentTransition11+

customNavContentTransition(delegate:(from: NavContentInfo, to: NavContentInfo, operation: NavigationOperation) => NavigationAnimatedTransition | undefined)

自定义转场动画回调。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
from NavContentInfo 退场Destination的页面。
to NavContentInfo 进场Destination的页面。
operation NavigationOperation 转场类型。

返回值:

展开
类型 说明
NavigationAnimatedTransition | undefined

自定义转场动画协议。

undefined: 返回未定义,执行默认转场动效。

Navigation路由栈,允许被继承12+。开发者可以在派生类中新增属性方法,也可以重写基类NavPathStack的方法。派生类对象可以替代基类NavPathStack对象使用。使用示例参见示例10

说明

1.连续调用多个页面栈操作方法时,中间过程会被忽略,显示最终的栈操作结果。

例如:在Page1页面先pop再push一个Page1,系统会认为操作前和操作后的结果一致而不进行任何操作,如果需要强行push一个Page1实例,可以使用NEW_INSTANCE模式。

2.不建议开发者通过监听生命周期的方式管理自己的页面栈。

constructor

constructor()

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

pushPath10+

pushPath(info: NavPathInfo, animated?: boolean): void

将info指定的NavDestination页面信息入栈。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
info NavPathInfo NavDestination页面的信息。
animated11+ boolean 是否支持转场动画,默认值:true。

pushPath12+

pushPath(info: NavPathInfo, options?: NavigationOptions): void

将info指定的NavDestination页面信息入栈,具体根据options中指定不同的LaunchMode,有不同的行为。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
info NavPathInfo NavDestination页面的信息。
options NavigationOptions 页面栈操作选项。

pushPathByName10+

pushPathByName(name: string, param: unknown, animated?: boolean): void

将name指定的NavDestination页面信息入栈,传递的数据为param。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
param unknown NavDestination页面详细参数。
animated11+ boolean 是否支持转场动画,默认值:true。

pushPathByName11+

pushPathByName(name: string, param: Object, onPop: Callback<PopInfo>, animated?: boolean): void

将name指定的NavDestination页面信息入栈,传递的数据为param,添加onPop回调接收入栈页面出栈时的返回结果,并进行处理。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
param Object NavDestination页面详细参数。
onPop Callback<PopInfo> Callback回调,用于页面出栈时触发该回调处理返回结果。仅pop中设置result参数后触发。
animated boolean 是否支持转场动画,默认值:true。

pushDestination11+

pushDestination(info: NavPathInfo, animated?: boolean): Promise<void>

将info指定的NavDestination页面信息入栈,使用Promise异步回调返回接口调用结果。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
info NavPathInfo NavDestination页面的信息。
animated boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
Promise<void> 异常返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码ohos.router(页面路由)错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.
100005 Builder function not registered.
100006 NavDestination not found.

pushDestination12+

pushDestination(info: NavPathInfo, options?: NavigationOptions): Promise<void>

将info指定的NavDestination页面信息入栈,使用Promise异步回调返回接口调用结果,具体根据options中指定不同的LaunchMode,有不同的行为。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
info NavPathInfo NavDestination页面的信息。
options NavigationOptions 页面栈操作选项。

返回值:

展开
类型 说明
Promise<void> 异常返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码ohos.router(页面路由)错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.
100005 Builder function not registered.
100006 NavDestination not found.

pushDestinationByName11+

pushDestinationByName(name: string, param: Object, animated?: boolean): Promise<void>

将name指定的NavDestination页面信息入栈,传递的数据为param,使用Promise异步回调返回接口调用结果。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
param Object NavDestination页面详细参数。
animated boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
Promise<void> 异常返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码ohos.router(页面路由)错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.
100005 Builder function not registered.
100006 NavDestination not found.

pushDestinationByName11+

pushDestinationByName(name: string, param: Object, onPop: Callback<PopInfo>, animated?: boolean): Promise<void>

将name指定的NavDestination页面信息入栈,传递的数据为param,并且添加用于页面出栈时处理返回结果的OnPop回调,使用Promise异步回调返回接口调用结果。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
param Object NavDestination页面详细参数。
onPop Callback<PopInfo> Callback回调,用于页面出栈时处理返回结果。仅pop中设置result参数后触发。
animated boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
Promise<void> 异常返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码ohos.router(页面路由)错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.
100005 Builder function not registered.
100006 NavDestination not found.

replacePath11+

replacePath(info: NavPathInfo, animated?: boolean): void

将当前页面栈栈顶退出,将info指定的NavDestination页面信息入栈。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
info NavPathInfo 新栈顶页面参数信息。
animated11+ boolean 是否支持转场动画,默认值:true。

replacePath12+

replacePath(info: NavPathInfo, options?: NavigationOptions): void

替换页面栈操作,具体根据options中指定不同的LaunchMode,有不同的行为。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
info NavPathInfo 新栈顶页面参数信息。
options NavigationOptions 页面栈操作选项。

replacePathByName11+

replacePathByName(name: string, param: Object, animated?: boolean): void

将当前页面栈栈顶退出,将name指定的页面入栈。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
param Object NavDestination页面详细参数。
animated11+ boolean 是否支持转场动画,默认值:true。

removeByIndexes11+

removeByIndexes(indexes: Array<number>): number

将页面栈内索引值在indexes中的NavDestination页面删除。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
indexes Array<number> 待删除NavDestination页面的索引值数组。

返回值:

展开
类型 说明
number 返回删除的NavDestination页面数量。

removeByName11+

removeByName(name: string): number

将页面栈内指定name的NavDestination页面删除。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string 删除的NavDestination页面的名字。

返回值:

展开
类型 说明
number 返回删除的NavDestination页面数量。

removeByNavDestinationId12+

removeByNavDestinationId(navDestinationId: string): boolean

将页面栈内指定navDestinationId的NavDestination页面删除。navDestinationId可以在NavDestination的onReady回调中获取,也可以在NavDestinationInfo中获取。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
navDestinationId string 删除的NavDestination页面的唯一标识符navDestinationId。

返回值:

展开
类型 说明
boolean 返回是否成功删除该页面,true为删除成功。

pop10+

pop(animated?: boolean): NavPathInfo | undefined

弹出路由栈栈顶元素。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
animated11+ boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
NavPathInfo 返回栈顶NavDestination页面的信息。
undefined 当路由栈为空时返回undefined。

pop11+

pop(result: Object, animated?: boolean): NavPathInfo | undefined

弹出路由栈栈顶元素,并触发onPop回调传入页面处理结果。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
result Object 页面自定义处理结果。不支持boolean类型。
animated boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
NavPathInfo 返回栈顶NavDestination页面的信息。
undefined 当路由栈为空时返回undefined。

popToName10+

popToName(name: string, animated?: boolean): number

回退路由栈到由栈底开始第一个名为name的NavDestination页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
animated11+ boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
number 如果栈中存在名为name的NavDestination页面,则返回由栈底开始第一个名为name的NavDestination页面的索引,否则返回-1。

popToName11+

popToName(name: string, result: Object, animated?: boolean): number

回退路由栈到由栈底开始第一个名为name的NavDestination页面,并触发onPop回调传入页面处理结果。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
result Object 页面自定义处理结果。不支持boolean类型。
animated boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
number 如果栈中存在名为name的NavDestination页面,则返回由栈底开始第一个名为name的NavDestination页面的索引,否则返回-1。

popToIndex10+

popToIndex(index: number, animated?: boolean): void

回退路由栈到index指定的NavDestination页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
index number NavDestination页面的位置索引。
animated11+ boolean 是否支持转场动画,默认值:true。

popToIndex11+

popToIndex(index: number, result: Object, animated?: boolean): void

回退路由栈到index指定的NavDestination页面,并触发onPop回调传入页面处理结果。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
index number NavDestination页面的位置索引。
result Object 页面自定义处理结果。不支持boolean类型。
animated boolean 是否支持转场动画,默认值:true。

moveToTop10+

moveToTop(name: string, animated?: boolean): number

将由栈底开始第一个名为name的NavDestination页面移到栈顶。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
animated11+ boolean 是否支持转场动画,默认值:true。

返回值:

展开
类型 说明
number 如果栈中存在名为name的NavDestination页面,则返回由栈底开始第一个名为name的NavDestination页面的当前索引,否则返回-1。

moveIndexToTop10+

moveIndexToTop(index: number, animated?: boolean): void

将index指定的NavDestination页面移到栈顶。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
index number NavDestination页面的位置索引。
animated11+ boolean 是否支持转场动画,默认值:true。

clear10+

clear(animated?: boolean): void

清除栈中所有页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
animated11+ boolean 是否支持转场动画,默认值:true。

getAllPathName10+

getAllPathName(): Array<string>

获取栈中所有NavDestination页面的名称。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

返回值:

展开
类型 说明
Array<string> 返回栈中所有NavDestination页面的名称。

getParamByIndex10+

getParamByIndex(index: number): unknown | undefined

获取index指定的NavDestination页面的参数信息。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
index number NavDestination页面的位置索引。

返回值:

展开
类型 说明
unknown 返回对应NavDestination页面的参数信息。
undefined 传入index无效时返回undefined。

getParamByName10+

getParamByName(name: string): Array<unknown>

获取全部名为name的NavDestination页面的参数信息。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。

返回值:

展开
类型 说明
Array<unknown> 返回全部名为name的NavDestination页面的参数信息。

getIndexByName10+

getIndexByName(name: string): Array<number>

获取全部名为name的NavDestination页面的位置索引。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
name string NavDestination页面名称。

返回值:

展开
类型 说明
Array<number> 返回全部名为name的NavDestination页面的位置索引。

size10+

size(): number

获取栈大小。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

返回值:

展开
类型 说明
number 返回栈大小。

disableAnimation11+

disableAnimation(value: boolean): void

关闭(true)或打开(false)当前Navigation中所有转场动画。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
value boolean 是否关闭转场动画,默认值:false。

getParent11+

getParent(): NavPathStack | null

获取父NavPathStack。

当出现Navigation嵌套Navigation的情况时(可以是直接嵌套,也可以是间接嵌套),内部Navigation的NavPathStack能够获取到外层Navigation的NavPathStack。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

返回值:

展开
类型 说明
NavPathStack | null 如果当前NavPathStack所属Navigation的外层有另外的一层Navigation,则能够获取到外层Navigation的NavPathStack。否则获取不到NavPathStack,返回null。

setInterception12+

setInterception(interception: NavigationInterception): void

设置Navigation页面跳转拦截回调。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
interception NavigationInterception 设置Navigation跳转拦截对象。

路由页面信息。

constructor

constructor(name: string, param: unknown, onPop?: Callback<PopInfo>, isEntry?: boolean)

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
参数名 类型 必填 说明
name string NavDestination页面名称。
param unknown NavDestination页面详细参数。
onPop11+ Callback<PopInfo> NavDestination页面触发pop时返回的回调。仅pop中设置result参数后触发。
isEntry12+ boolean

标记NavDestination是否为入口页面。

默认值:false

标记清理时机:1、在当前navDestination页面触发一次全局back事件。2、应用退至后台。

说明

入口NavDestination不响应应用内的全局back事件,直接触发应用间的全局back事件。

属性

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
name string

NavDestination页面名称。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

param unknown

NavDestination页面详细参数。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

onPop11+ Callback<PopInfo>

NavDestination页面触发pop时返回的回调。仅pop中设置result参数后触发。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

isEntry12+ boolean

标记NavDestination是否为入口页面。

默认值:false

标记清理时机:1、在当前navDestination页面触发一次全局back事件。2、应用退至后台。

说明

入口NavDestination不响应应用内的全局back事件,直接触发应用间的全局back事件。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

PopInfo11+

下一个页面返回的回调信息载体。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
info NavPathInfo 页面触发返回时的当前页面信息,系统自动获取填入,无需开发者传入。
result Object 页面触发返回时的结果,开发者自定义对象。

跳转Destination信息。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
name string NavDestination名称,如果为根视图(NavBar),则返回值为undefined。
index number NavDestination在NavPathStack中的序号, 如果为根视图(NavBar),则返回值为 -1。
mode NavDestinationMode NavDestination的模式,如果是根视图(NavBar),则返回值为undefined。
param12+ Object NavDestination页面加载的参数。
navDestinationId12+ string NavDestination的唯一标识符。

自定义转场动画协议,开发者需实现该协议来定义Navigation路由跳转的跳转动画。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
timeout number

动画超时结束时间。

单位:ms。

默认值:可交互动画无默认值,不可交互动画默认超时时间为1000ms。

transition (transitionProxy : NavigationTransitionProxy) => void

自定义转场动画执行回调。

transitionProxy: 自定义转场动画代理对象。

onTransitionEnd (success: boolean) => void

转场完成回调。

success: 转场是否成功。

isInteractive12+ boolean

本次转场动画是否为可交互转场。

默认值:false。

自定义转场动画代理对象。

系统能力: SystemCapability.ArkUI.ArkUI.Full

属性

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
from NavContentInfo 退场页面信息。
to NavContentInfo 进场页面信息。
isInteractive12+ boolean 是否为可交互转场动画。

finishTransition

finishTransition(): void;

结束本次自定义转场动画,开发者需要主动触发该方法来结束本次转场,否则系统会在timeout的时间后结束本次转场。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

cancelTransition12+

cancelTransition?(): void;

取消本次交互转场,恢复到页面跳转前的页面栈(不支持取消不可交互转场动画)。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

updateTransition12+

updateTransition?(progress: number): void;

更新交互转场动画进度(不可交互动画不支持动画进度设置)。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

展开
参数名 类型 必填 说明
progress number 设置交互转场动画进度百分比。取值范围 0-1。

Navigation跳转拦截对象。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
willShow InterceptionShowCallback 页面跳转前拦截,允许操作栈,在当前跳转中生效。
didShow InterceptionShowCallback 页面跳转后回调。在该回调中操作栈在下一次跳转中刷新。
modeChange InterceptionModeCallback Navigation单双栏显示状态发生变更时触发该回调。

InterceptionShowCallback12+

type InterceptionShowCallback = (from: NavDestinationContext|NavBar, to: NavDestinationContext|NavBar, operation: NavigationOperation, isAnimated: boolean) => void

navigation页面跳转前和页面跳转后的拦截回调。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
参数名 类型 必填 说明
from NavDestinationContext |NavBar 页面跳转之前的栈顶页面信息。参数值为navBar,则表示跳转前的页面为Navigation首页。
to NavDestinationContext |NavBar 页面跳转之后的栈顶页面信息。参数值为navBar,则表示跳转的目标页面为Navigation首页。
operation NavigationOperation 当前页面跳转类型。
isAnimated boolean 页面跳转是否有动画。

InterceptionModeCallback12+

type InterceptionModeCallback = (mode: NavigationMode) => void

navigation单双栏显示状态发生变更时的拦截回调。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
参数名 类型 必填 说明
mode NavigationMode 导航栏的显示模式。

type NavBar = 'navBar'

Navigation首页名字。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
类型 说明
'navBar' Navigation首页。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
value string | Resource14+

API Version 9: 显示菜单栏单个选项的文本。

API Version 10: 不显示菜单栏单个选项的文本。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

icon string | Resource14+

菜单栏单个选项的图标资源路径。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

isEnabled12+ boolean

使能状态,默认使能(false未使能,true使能)。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

action () => void

当前选项被选中的事件回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

symbolIcon12+ SymbolGlyphModifier

菜单栏单个选项的symbol资源(优先级高于icon)。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

ToolbarItem10+

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
value ResourceStr 工具栏单个选项的显示文本。
icon ResourceStr 工具栏单个选项的图标资源路径。
action () => void 当前选项被选中的事件回调。
status ToolbarItemStatus

工具栏单个选项的状态。

默认值:ToolbarItemStatus.NORMAL

activeIcon ResourceStr 工具栏单个选项处于ACTIVE态时的图标资源路径。
symbolIcon12+ SymbolGlyphModifier

工具栏单个选项的symbol资源(优先级高于icon)。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

activeSymbolIcon12+ SymbolGlyphModifier

工具栏单个选项处于ACTIVE态时的symbol资源(优先级高于activeIcon)。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

ToolbarItemStatus10+枚举说明

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 说明
NORMAL 设置工具栏单个选项为NORMAL态,该选项显示默认样式,可以触发Hover,Press,Focus事件并显示对应的多态样式。
DISABLED 设置工具栏单个选项为DISABLED态, 该选项显示DISABLED态样式,并且不可交互。
ACTIVE 设置工具栏单个选项为ACTIVE态, 该选项通过点击事件可以将icon图标更新为activeIcon对应的图片资源。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 说明
Free

当内容为满一屏的可滚动组件时,标题随着内容向上滚动而缩小(子标题的大小不变、淡出)。向下滚动内容到顶时则恢复原样。

说明:

标题随着内容滚动大小联动的动效在title设置为ResourceStr和NavigationCommonTitle时生效,设置成其余自定义节点类型时字体样式无法变化,下拉时只影响标题栏偏移。

可滚动组件不满一屏时,如果想使用联动效果,就要使用滚动组件提供的edgeEffect接口将options参数设置为true。未滚动状态,标题栏高度与Full模式一致;滚动时,标题栏的最小高度与Mini模式一致。

Mini

固定为小标题模式。

默认值:API version 12之前,只有主标题时,标题栏高度为56vp;同时有主标题和副标题时,标题栏高度为82vp。从API version 12开始,该模式下标题栏高度为56vp。

Full

固定为大标题模式。

默认值:只有主标题时,标题栏高度为112vp;同时有主标题和副标题时,标题栏高度为138vp。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
main string | Resource14+ 设置主标题。
sub string | Resource14+ 设置副标题。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
builder CustomBuilder 设置标题栏内容。
height TitleHeight | Length 设置标题栏高度。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 说明
Start 双栏显示时,主列在主轴方向首部。
End 双栏显示时,主列在主轴方向尾部。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 说明
Stack 导航栏与内容区独立显示,相当于两个页面。
Split

导航栏与内容区分两栏显示。

以下navBarWidthRange的值用[minNavBarWidth,maxNavBarWidth]表示

1.当navBarWidth属性的值,在navBarWidthRange属性的值范围以外时,navBarWidth按如下规则显示:

navBarWidth < minNavBarWidth时,navBarWidth修正为minNavBarWidth;

navBarWidth > maxNavBarWidth,且组件宽度 - minContentWidth - 分割线宽度(1vp) > maxNavBarWidth时,navBarWidth修正为maxNavBarWidth;

navBarWidth > maxNavBarWidth,且组件宽度 - minContentWidth - 分割线宽度(1vp) < minNavBarWidth时,navBarWidth修正为minNavBarWidth;

navBarWidth > maxNavBarWidth,且组件宽度 - minContentWidth - 分割线宽度(1vp)在navBarWidthRange范围内,navBarWidth修正为组件宽度 - 分割线宽度(1vp) - minContentWidth。

2.当navBarWidth属性的值,在navBarWidthRange属性的值范围以内时,navBarWidth按如下规则显示:

minNavBarWidth + minContentWidth + 分割线宽度(1vp) >= 组件宽度时,navBarWidth修正为minNavBarWidth;

minNavBarWidth + minContentWidth + 分割线宽度(1vp) < 组件宽度,且navBarWidth + minContentWidth + 分割线宽度(1vp) >= 组件宽度时,navBarWidth修正为组件宽度 - 分割线宽度(1vp) - minContentWidth;

minNavBarWidth + minContentWidth + 分割线宽度(1vp) < 组件宽度,且navBarWidth + minContentWidth + 分割线宽度(1vp) < 组件宽度时,navBarWidth为设置的值。

3.缩小组件尺寸时,先缩小内容区的尺寸至minContentWidth,然后再缩小导航栏的尺寸至minNavBarWidth。若继续缩小,先缩小内容区,内容区消失后再缩小导航栏。

4.设置导航栏为固定尺寸时,若持续缩小组件尺寸,导航栏最后压缩显示。

5.若只设置了navBarWidth属性,则导航栏宽度为navBarWidth,且分割线不可拖动。

Auto

API version 9之前:窗口宽度>=520vp时,采用Split模式显示;窗口宽度<520vp时,采用Stack模式显示。

API version 10及以上:窗口宽度>=600vp时,采用Split模式显示;窗口宽度<600vp时,采用Stack模式显示,600vp等于minNavBarWidth(240vp) + minContentWidth (360vp)。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 说明
PUSH 本次转场为页面进场。
POP 本次转场为页面退场。
REPLACE 本次转场为页面替换。

BarStyle12+枚举说明

标题栏或工具栏的布局样式。NavDestination的工具栏不支持设置该属性。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 说明
STANDARD

指定该模式的标题栏或工具栏与内容区采用上下布局。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

STACK

指定该模式的标题栏或工具栏与内容区采用层叠布局,标题栏或工具栏布局在内容区上层。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

SAFE_AREA_PADDING14+

将指定该模式的标题栏或工具栏设置为组件级安全区

元服务API: 从API version 14开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
backgroundColor ResourceColor

标题栏背景颜色,不设置时为系统默认颜色。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

backgroundBlurStyle BlurStyle

标题栏背景模糊样式,不设置时关闭背景模糊效果。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

barStyle12+ BarStyle

设置标题栏布局方式。

默认值:BarStyle.STANDARD

元服务API: 从API version 12开始,该接口支持在元服务中使用。

paddingStart12+ LengthMetrics

标题栏起始端内间距。

仅支持以下任一场景:

1. 显示返回图标,即hideBackButton为false;

2. 使用非自定义标题,即标题value类型为ResourceStr或NavigationCommonTitle。

默认值:

LengthMetrics.resource($r('sys.float.margin_left'))。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

paddingEnd12+ LengthMetrics

标题栏结束端内间距。

仅支持以下任一场景:

1. 使用非自定义菜单,即菜单value为Array<NavigationMenuItem>;

2. 没有右上角菜单,且使用非自定义标题,即标题value类型为ResourceStr或NavigationCommonTitle。

默认值:

LengthMetrics.resource($r('sys.float.margin_right'))。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

mainTitleModifier13+ TextModifier

主标题属性修改器。

有如下几点使用规则:

1. 通过Modifier设置的属性会覆盖系统默认的属性(如果Modifier设置了fontSize, maxFontSize, minFontSize任一属性,则系统设置的大小相关属性不生效,以开发者的设置为准);

2. 不设该属性或者设置了异常值,则恢复系统默认设置;

3. Free模式下设置字体大小时,原有滑动改变标题大小的效果失效。

元服务API: 从API version 13开始,该接口支持在元服务中使用。

subTitleModifier13+ TextModifier

子标题属性修改器。

有如下几点使用规则:

1. 通过Modifier设置的属性会覆盖系统默认的属性(如果Modifier设置了fontSize, maxFontSize, minFontSize任一属性,则系统设置的大小相关属性不生效,以开发者的设置为准);

2. 不设该属性或者设置了异常值,则恢复系统默认设置。

元服务API: 从API version 13开始,该接口支持在元服务中使用。

enableHoverMode13+ boolean

是否响应悬停态。

使用规则:

1. 需满足Navigation为全屏大小;

2. 标题栏显示模式为Free时或者标题栏布局方式为STANDARD时,此接口设置无效。

默认值:false。

元服务API: 从API version 13开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
backgroundColor ResourceColor

工具栏背景颜色,不设置时为系统默认颜色。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

backgroundBlurStyle BlurStyle

工具栏背景模糊样式,不设置时关闭背景模糊效果。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

barStyle14+ BarStyle

设置工具栏布局方式。

元服务API: 从API version 14开始,该接口支持在元服务中使用。

LaunchMode12+枚举说明

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 说明
STANDARD

系统默认的栈操作模式。

push操作会将指定的NavDestination入栈;replace操作会将当前栈顶NavDestination替换。

MOVE_TO_TOP_SINGLETON 从栈底向栈顶查找,如果指定的名称已经存在,则将对应的NavDestination页面移到栈顶(replace操作会将最后的栈顶替换成指定的NavDestination),否则行为和STANDARD一致。
POP_TO_SINGLETON 从栈底向栈顶查找,如果指定的名称已经存在,则将其上方的NavDestination页面全部移除(replace操作会将最后的栈顶替换成指定的NavDestination),否则行为和STANDARD一致。
NEW_INSTANCE 创建新的NavDestination实例。与STANDARD模式相比,该方法不会复用栈中同名实例。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
名称 类型 必填 说明
launchMode LaunchMode

页面栈的操作模式。

默认值:LaunchMode.STANDARD

animated boolean

是否支持转场动画。

默认值:true。

SystemBarStyle12+

type SystemBarStyle = SystemBarStyle

状态栏的属性。在设置页面级状态栏属性时使用。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

展开
类型 说明
SystemBarStyle 状态栏文字颜色。默认值:'#0xE5FFFFFF'。

示例

示例效果请以真机为准,系统路由表不支持预览器,跨平台以及模拟器。

示例1(Navigation页面布局)

该示例主要演示Navigation页面的布局包括标题栏(title),菜单栏(menus),内容区和工具栏(toolbarConfiguration)。

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. class A {
  3. text: string = ''
  4. num: number = 0
  5. }
  6. @Entry
  7. @Component
  8. struct NavigationExample {
  9. private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  10. @State currentIndex: number = 0
  11. @Builder
  12. NavigationTitle() {
  13. Column() {
  14. Text('Title')
  15. .fontColor('#182431')
  16. .fontSize(30)
  17. .lineHeight(41)
  18. .fontWeight(700)
  19. Text('subtitle')
  20. .fontColor('#182431')
  21. .fontSize(14)
  22. .lineHeight(19)
  23. .opacity(0.4)
  24. .margin({ top: 2, bottom: 20 })
  25. }.alignItems(HorizontalAlign.Start)
  26. }
  27. @Builder
  28. NavigationMenus() {
  29. Row() {
  30. Image('resources/base/media/ic_public_add.svg')
  31. .width(24)
  32. .height(24)
  33. Image('resources/base/media/ic_public_add.svg')
  34. .width(24)
  35. .height(24)
  36. .margin({ left: 24 })
  37. Image('common/ic_public_more.svg')
  38. .width(24)
  39. .height(24)
  40. .margin({ left: 24 })
  41. }
  42. }
  43. build() {
  44. Column() {
  45. Navigation() {
  46. TextInput({ placeholder: 'search...' })
  47. .width('90%')
  48. .height(40)
  49. .backgroundColor('#FFFFFF')
  50. .margin({ top: 8 })
  51. List({ space: 12, initialIndex: 0 }) {
  52. ForEach(this.arr, (item: number) => {
  53. ListItem() {
  54. Text('' + item)
  55. .width('90%')
  56. .height(72)
  57. .backgroundColor('#FFFFFF')
  58. .borderRadius(24)
  59. .fontSize(16)
  60. .fontWeight(500)
  61. .textAlign(TextAlign.Center)
  62. }
  63. }, (item: number) => item.toString())
  64. }
  65. .height(324)
  66. .width('100%')
  67. .margin({ top: 12, left: '10%' })
  68. }
  69. .title(this.NavigationTitle)
  70. .menus(this.NavigationMenus)
  71. .titleMode(NavigationTitleMode.Full)
  72. .toolbarConfiguration([
  73. {
  74. value: $r("app.string.navigation_toolbar_add"),
  75. icon: $r("app.media.ic_public_highlightsed")
  76. },
  77. {
  78. value: $r("app.string.navigation_toolbar_app"),
  79. icon: $r("app.media.ic_public_highlights")
  80. },
  81. {
  82. value: $r("app.string.navigation_toolbar_collect"),
  83. icon: $r("app.media.ic_public_highlights")
  84. }
  85. ])
  86. .hideTitleBar(false)
  87. .hideToolBar(false)
  88. .onTitleModeChange((titleModel: NavigationTitleMode) => {
  89. console.info('titleMode' + titleModel)
  90. })
  91. }.width('100%').height('100%').backgroundColor('#F1F3F5')
  92. }
  93. }

示例2(使用路由栈方法)

该示例主要演示NavPathStack中方法的使用及路由拦截。

收起
自动换行
深色代码主题
复制
  1. // Index.ets
  2. @Entry
  3. @Component
  4. struct NavigationExample {
  5. pageInfos: NavPathStack = new NavPathStack()
  6. isUseInterception: boolean = false;
  7. registerInterception() {
  8. this.pageInfos.setInterception({
  9. // 页面跳转前拦截,允许操作栈,在当前跳转中生效。
  10. willShow: (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar",
  11. operation: NavigationOperation, animated: boolean) => {
  12. if (!this.isUseInterception) {
  13. return;
  14. }
  15. if (typeof to === "string") {
  16. console.log("target page is navigation home");
  17. return;
  18. }
  19. // 重定向目标页面,更改为pageTwo页面到pageOne页面。
  20. let target: NavDestinationContext = to as NavDestinationContext;
  21. if (target.pathInfo.name === 'pageTwo') {
  22. target.pathStack.pop();
  23. target.pathStack.pushPathByName('pageOne', null);
  24. }
  25. },
  26. // 页面跳转后回调,在该回调中操作栈在下一次跳转中刷新。
  27. didShow: (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar",
  28. operation: NavigationOperation, isAnimated: boolean) => {
  29. if (!this.isUseInterception) {
  30. return;
  31. }
  32. if (typeof from === "string") {
  33. console.log("current transition is from navigation home");
  34. } else {
  35. console.log(`current transition is from ${(from as NavDestinationContext).pathInfo.name}`)
  36. }
  37. if (typeof to === "string") {
  38. console.log("current transition to is navBar");
  39. } else {
  40. console.log(`current transition is to ${(to as NavDestinationContext).pathInfo.name}`);
  41. }
  42. },
  43. // Navigation单双栏显示状态发生变更时触发该回调。
  44. modeChange: (mode: NavigationMode) => {
  45. if (!this.isUseInterception) {
  46. return;
  47. }
  48. console.log(`current navigation mode is ${mode}`);
  49. }
  50. })
  51. }
  52. build() {
  53. Navigation(this.pageInfos) {
  54. Column() {
  55. Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
  56. .width('80%')
  57. .height(40)
  58. .margin(20)
  59. .onClick(() => {
  60. this.pageInfos.pushPath({ name: 'pageOne' }) //将name指定的NavDestination页面信息入栈
  61. })
  62. Button('use interception', { stateEffect: true, type: ButtonType.Capsule })
  63. .width('80%')
  64. .height(40)
  65. .margin(20)
  66. .onClick(() => {
  67. this.isUseInterception = !this.isUseInterception;
  68. if (this.isUseInterception) {
  69. this.registerInterception();
  70. } else {
  71. this.pageInfos.setInterception(undefined);
  72. }
  73. })
  74. }
  75. }.title('NavIndex')
  76. }
  77. }
收起
自动换行
深色代码主题
复制
  1. // PageOne.ets
  2. class TmpClass {
  3. count: number = 10
  4. }
  5. @Builder
  6. export function PageOneBuilder(name: string, param: Object) {
  7. PageOne()
  8. }
  9. @Component
  10. export struct PageOne {
  11. pageInfos: NavPathStack = new NavPathStack()
  12. build() {
  13. NavDestination() {
  14. Column() {
  15. Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
  16. .width('80%')
  17. .height(40)
  18. .margin(20)
  19. .onClick(() => {
  20. let tmp = new TmpClass()
  21. this.pageInfos.pushPathByName('pageTwo', tmp) //将name指定的NavDestination页面信息入栈,传递的数据为param
  22. })
  23. Button('singletonLaunchMode', { stateEffect: true, type: ButtonType.Capsule })
  24. .width('80%')
  25. .height(40)
  26. .margin(20)
  27. .onClick(() => {
  28. this.pageInfos.pushPath({ name: 'pageOne' },
  29. { launchMode: LaunchMode.MOVE_TO_TOP_SINGLETON }) //从栈底向栈顶查找,如果指定的名称已经存在,则将对应的NavDestination页面移到栈顶
  30. })
  31. Button('popToname', { stateEffect: true, type: ButtonType.Capsule })
  32. .width('80%')
  33. .height(40)
  34. .margin(20)
  35. .onClick(() => {
  36. this.pageInfos.popToName('pageTwo') //回退路由栈到第一个名为name的NavDestination页面
  37. console.log('popToName' + JSON.stringify(this.pageInfos),
  38. '返回值' + JSON.stringify(this.pageInfos.popToName('pageTwo')))
  39. })
  40. Button('popToIndex', { stateEffect: true, type: ButtonType.Capsule })
  41. .width('80%')
  42. .height(40)
  43. .margin(20)
  44. .onClick(() => {
  45. this.pageInfos.popToIndex(1) // 回退路由栈到index指定的NavDestination页面
  46. console.log('popToIndex' + JSON.stringify(this.pageInfos))
  47. })
  48. Button('moveToTop', { stateEffect: true, type: ButtonType.Capsule })
  49. .width('80%')
  50. .height(40)
  51. .margin(20)
  52. .onClick(() => {
  53. this.pageInfos.moveToTop('pageTwo') // 将第一个名为name的NavDestination页面移到栈顶
  54. console.log('moveToTop' + JSON.stringify(this.pageInfos),
  55. '返回值' + JSON.stringify(this.pageInfos.moveToTop('pageTwo')))
  56. })
  57. Button('moveIndexToTop', { stateEffect: true, type: ButtonType.Capsule })
  58. .width('80%')
  59. .height(40)
  60. .margin(20)
  61. .onClick(() => {
  62. this.pageInfos.moveIndexToTop(1) // 将index指定的NavDestination页面移到栈顶
  63. console.log('moveIndexToTop' + JSON.stringify(this.pageInfos))
  64. })
  65. Button('clear', { stateEffect: true, type: ButtonType.Capsule })
  66. .width('80%')
  67. .height(40)
  68. .margin(20)
  69. .onClick(() => {
  70. this.pageInfos.clear() //清除栈中所有页面
  71. })
  72. Button('get', { stateEffect: true, type: ButtonType.Capsule })
  73. .width('80%')
  74. .height(40)
  75. .margin(20)
  76. .onClick(() => {
  77. console.log('-------------------')
  78. console.log('获取栈中所有NavDestination页面的名称', JSON.stringify(this.pageInfos.getAllPathName()))
  79. console.log('获取index指定的NavDestination页面的参数信息',
  80. JSON.stringify(this.pageInfos.getParamByIndex(1)))
  81. console.log('获取全部名为name的NavDestination页面的参数信息',
  82. JSON.stringify(this.pageInfos.getParamByName('pageTwo')))
  83. console.log('获取全部名为name的NavDestination页面的位置索引',
  84. JSON.stringify(this.pageInfos.getIndexByName('pageOne')))
  85. console.log('获取栈大小', JSON.stringify(this.pageInfos.size()))
  86. })
  87. }.width('100%').height('100%')
  88. }.title('pageOne')
  89. .onBackPressed(() => {
  90. const popDestinationInfo = this.pageInfos.pop() // 弹出路由栈栈顶元素
  91. console.log('pop' + '返回值' + JSON.stringify(popDestinationInfo))
  92. return true
  93. }).onReady((context: NavDestinationContext) => {
  94. this.pageInfos = context.pathStack
  95. })
  96. }
  97. }
收起
自动换行
深色代码主题
复制
  1. // PageTwo.ets
  2. @Builder
  3. export function PageTwoBuilder(name: string, param: Object) {
  4. PageTwo()
  5. }
  6. @Component
  7. export struct PageTwo {
  8. pathStack: NavPathStack = new NavPathStack()
  9. private menuItems: Array<NavigationMenuItem> = [
  10. {
  11. value: "1",
  12. icon: 'resources/base/media/undo.svg',
  13. },
  14. {
  15. value: "2",
  16. icon: 'resources/base/media/redo.svg',
  17. isEnabled: false,
  18. },
  19. {
  20. value: "3",
  21. icon: 'resources/base/media/ic_public_ok.svg',
  22. isEnabled: true,
  23. }
  24. ]
  25. build() {
  26. NavDestination() {
  27. Column() {
  28. Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
  29. .width('80%')
  30. .height(40)
  31. .margin(20)
  32. .onClick(() => {
  33. this.pathStack.pushPathByName('pageOne', null)
  34. })
  35. }.width('100%').height('100%')
  36. }.title('pageTwo')
  37. .menus(this.menuItems)
  38. .onBackPressed(() => {
  39. this.pathStack.pop()
  40. return true
  41. })
  42. .onReady((context: NavDestinationContext) => {
  43. this.pathStack = context.pathStack;
  44. console.log("current page config info is " + JSON.stringify(context.getConfigInRouteMap()))
  45. })
  46. }
  47. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "pageOne",
  7. "pageSourceFile": "src/main/ets/pages/PageOne.ets",
  8. "buildFunction": "PageOneBuilder",
  9. "data": {
  10. "description": "this is pageOne"
  11. }
  12. },
  13. {
  14. "name": "pageTwo",
  15. "pageSourceFile": "src/main/ets/pages/PageTwo.ets",
  16. "buildFunction": "PageTwoBuilder"
  17. }
  18. ]
  19. }

示例3(设置可交互转场动画)

该示例主要演示设置每个NavDestination子页面的自定义转场动画及可交互转场动画。

收起
自动换行
深色代码主题
复制
  1. // Index.ets
  2. import { CustomTransition, AnimateCallback } from './CustomNavigationUtils'
  3. @Entry
  4. @Component
  5. struct NavigationExample {
  6. pageInfos: NavPathStack = new NavPathStack();
  7. aboutToAppear() {
  8. if (this.pageInfos === undefined) {
  9. this.pageInfos = new NavPathStack();
  10. }
  11. this.pageInfos.pushPath({ name: 'pageOne', param: CustomTransition.getInstance().getAnimationId() });
  12. }
  13. build() {
  14. Navigation(this.pageInfos) {
  15. }
  16. .title('NavIndex')
  17. .hideNavBar(true)
  18. .customNavContentTransition((from: NavContentInfo, to: NavContentInfo, operation: NavigationOperation) => {
  19. if (from.mode == NavDestinationMode.DIALOG || to.mode == NavDestinationMode.DIALOG) {
  20. return undefined;
  21. }
  22. // 首页不进行自定义动画
  23. if (from.index === -1 || to.index === -1) {
  24. return undefined;
  25. }
  26. CustomTransition.getInstance().operation = operation;
  27. if (CustomTransition.getInstance().interactive) {
  28. let customAnimation: NavigationAnimatedTransition = {
  29. onTransitionEnd: (isSuccess: boolean) => {
  30. console.log("===== current transition is " + isSuccess);
  31. CustomTransition.getInstance().recoverState();
  32. CustomTransition.getInstance().proxy = undefined;
  33. },
  34. transition: (transitionProxy: NavigationTransitionProxy) => {
  35. CustomTransition.getInstance().proxy = transitionProxy;
  36. let targetIndex: string | undefined = operation == NavigationOperation.PUSH ?
  37. (to.navDestinationId) : (from.navDestinationId);
  38. if (targetIndex) {
  39. CustomTransition.getInstance().fireInteractiveAnimation(targetIndex, operation);
  40. }
  41. },
  42. isInteractive: CustomTransition.getInstance().interactive
  43. }
  44. return customAnimation;
  45. }
  46. let customAnimation: NavigationAnimatedTransition = {
  47. onTransitionEnd: (isSuccess: boolean) => {
  48. console.log(`current transition result is ${isSuccess}`)
  49. },
  50. timeout: 7000,
  51. // 转场开始时系统调用该方法,并传入转场上下文代理对象
  52. transition: (transitionProxy: NavigationTransitionProxy) => {
  53. if (!from.navDestinationId || !to.navDestinationId) {
  54. return;
  55. }
  56. // 从封装类CustomTransition中根据子页面的序列获取对应的转场动画回调
  57. let fromParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(from.navDestinationId);
  58. let toParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(to.navDestinationId);
  59. if (operation == NavigationOperation.PUSH) {
  60. if (toParam.start) {
  61. toParam.start(true, false);
  62. }
  63. animateTo({
  64. duration: 500, onFinish: () => {
  65. transitionProxy.finishTransition();
  66. }
  67. }, () => {
  68. if (toParam.finish) {
  69. toParam.finish(true, false);
  70. }
  71. })
  72. } else {
  73. if (fromParam.start) {
  74. fromParam.start(true, true);
  75. }
  76. animateTo({
  77. duration: 500, onFinish: () => {
  78. transitionProxy.finishTransition();
  79. }
  80. }, () => {
  81. if (fromParam.finish) {
  82. fromParam.finish(true, true);
  83. }
  84. })
  85. }
  86. }
  87. };
  88. return customAnimation;
  89. })
  90. }
  91. }
收起
自动换行
深色代码主题
复制
  1. // PageOne.ets
  2. import { CustomTransition } from './CustomNavigationUtils';
  3. @Builder
  4. export function PageOneBuilder(name: string, param: Object) {
  5. PageOne()
  6. }
  7. @Component
  8. export struct PageOne {
  9. pageInfos: NavPathStack = new NavPathStack();
  10. @State translateX: string = '0';
  11. pageId: string = '';
  12. rectWidth: number = 0;
  13. interactive: boolean = false;
  14. registerCallback() {
  15. CustomTransition.getInstance().registerNavParam(this.pageId, (isPush: boolean, isExit: boolean) => {
  16. if (isPush) {
  17. this.translateX = '100%';
  18. } else {
  19. this.translateX = '0';
  20. }
  21. }, (isPush: boolean, isExit: boolean) => {
  22. if (isPush) {
  23. this.translateX = '0';
  24. } else {
  25. this.translateX = '100%';
  26. }
  27. }, (isPush: boolean, isExit: boolean) => {
  28. this.translateX = '0';
  29. }, (operation: NavigationOperation) => {
  30. if (operation == NavigationOperation.PUSH) {
  31. this.translateX = '100%';
  32. animateTo({
  33. duration: 1000,
  34. onFinish: () => {
  35. this.translateX = '0';
  36. }
  37. }, () => {
  38. this.translateX = '0';
  39. })
  40. } else {
  41. this.translateX = '0';
  42. animateTo({
  43. duration: 1000,
  44. onFinish: () => {
  45. this.translateX = '0';
  46. }
  47. }, () => {
  48. this.translateX = '100%';
  49. })
  50. }
  51. }, 200);
  52. }
  53. build() {
  54. NavDestination() {
  55. Column() {
  56. Button(`setInteractive`)
  57. .onClick(() => {
  58. CustomTransition.getInstance().interactive = !CustomTransition.getInstance().interactive;
  59. this.interactive = CustomTransition.getInstance().interactive;
  60. })
  61. Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
  62. .width('80%')
  63. .height(40)
  64. .margin(20)
  65. .onClick(() => {
  66. //将name指定的NavDestination页面信息入栈,传递的数据为param
  67. this.pageInfos.pushDestinationByName('pageTwo', CustomTransition.getInstance().getAnimationId());
  68. })
  69. }
  70. .size({ width: '100%', height: '100%' })
  71. }
  72. .title('pageOne')
  73. .onDisAppear(() => {
  74. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
  75. })
  76. .onReady((context: NavDestinationContext) => {
  77. this.pageInfos = context.pathStack;
  78. if (context.navDestinationId) {
  79. this.pageId = context.navDestinationId;
  80. this.registerCallback();
  81. }
  82. })
  83. .translate({ x: this.translateX })
  84. .backgroundColor('#F1F3F5')
  85. .gesture(PanGesture()
  86. .onActionStart((event: GestureEvent) => {
  87. this.rectWidth = event.target.area.width as number;
  88. if (event.offsetX < 0) {
  89. this.pageInfos.pushPath({ name: 'pageTwo', param: CustomTransition.getInstance().getAnimationId() });
  90. } else {
  91. this.pageInfos.pop();
  92. }
  93. })
  94. .onActionUpdate((event: GestureEvent) => {
  95. let rate = event.fingerList[0].localX / this.rectWidth;
  96. CustomTransition.getInstance().updateProgress(rate);
  97. })
  98. .onActionEnd((event: GestureEvent) => {
  99. let rate: number = event.fingerList[0].localX / this.rectWidth;
  100. CustomTransition.getInstance().finishInteractiveAnimation(rate);
  101. }))
  102. }
  103. }
收起
自动换行
深色代码主题
复制
  1. // PageTwo.ets
  2. import { CustomTransition } from './CustomNavigationUtils'
  3. @Builder
  4. export function PageTwoBuilder(name: string, param: Object) {
  5. PageTwo({ param: param as number })
  6. }
  7. @Component
  8. export struct PageTwo {
  9. pageInfos: NavPathStack = new NavPathStack();
  10. @State translateX: string = '0';
  11. pageId: string = '';
  12. rectWidth: number = 0;
  13. param: number = 0;
  14. registerCallback() {
  15. CustomTransition.getInstance().registerNavParam(this.pageId, (isPush: boolean, isExit: boolean) => {
  16. if (isPush) {
  17. this.translateX = '100%'
  18. } else {
  19. this.translateX = '0';
  20. }
  21. }, (isPush: boolean, isExit: boolean) => {
  22. if (isPush) {
  23. this.translateX = '0';
  24. } else {
  25. this.translateX = '100%'
  26. }
  27. }, (isPush: boolean, isExit: boolean) => {
  28. this.translateX = '0';
  29. }, (operation: NavigationOperation) => {
  30. if (operation == NavigationOperation.PUSH) {
  31. this.translateX = '100%';
  32. animateTo({
  33. duration: 500, onFinish: () => {
  34. this.translateX = '0';
  35. }
  36. }, () => {
  37. this.translateX = '0'
  38. })
  39. } else {
  40. this.translateX = '0';
  41. animateTo({
  42. duration: 500, onFinish: () => {
  43. this.translateX = "0"
  44. }
  45. }, () => {
  46. this.translateX = '100%';
  47. })
  48. }
  49. }, 2000)
  50. }
  51. build() {
  52. NavDestination() {
  53. Column() {
  54. Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
  55. .width('80%')
  56. .height(40)
  57. .margin(20)
  58. .onClick(() => {
  59. //将name指定的NavDestination页面信息入栈,传递的数据为param
  60. this.pageInfos.pushPath({ name: 'pageOne', param: CustomTransition.getInstance().getAnimationId() })
  61. })
  62. }
  63. .size({ width: '100%', height: '100%' })
  64. }
  65. .title('pageTwo')
  66. .gesture(PanGesture()
  67. .onActionStart((event: GestureEvent) => {
  68. this.rectWidth = event.target.area.width as number;
  69. if (event.offsetX < 0) {
  70. this.pageInfos.pushPath({ name: 'pageOne', param: CustomTransition.getInstance().getAnimationId() });
  71. } else {
  72. this.pageInfos.pop();
  73. }
  74. })
  75. .onActionUpdate((event: GestureEvent) => {
  76. let rate = event.fingerList[0].localX / this.rectWidth;
  77. CustomTransition.getInstance().updateProgress(rate);
  78. })
  79. .onActionEnd((event: GestureEvent) => {
  80. let rate = event.fingerList[0].localX / this.rectWidth;
  81. CustomTransition.getInstance().finishInteractiveAnimation(rate);
  82. }))
  83. .onAppear(() => {
  84. this.registerCallback();
  85. })
  86. .onDisAppear(() => {
  87. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
  88. })
  89. .onReady((context: NavDestinationContext) => {
  90. this.pageInfos = context.pathStack;
  91. if (context.navDestinationId) {
  92. this.pageId = context.navDestinationId;
  93. this.registerCallback();
  94. }
  95. })
  96. .translate({ x: this.translateX })
  97. .backgroundColor(Color.Yellow)
  98. }
  99. }
收起
自动换行
深色代码主题
复制
  1. // CustomNavigationUtils.ets
  2. // 自定义接口,用来保存某个页面相关的转场动画回调和参数
  3. export interface AnimateCallback {
  4. finish: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined;
  5. start: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined;
  6. onFinish: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined;
  7. interactive: ((operation: NavigationOperation) => void | undefined) | undefined;
  8. timeout: (number | undefined) | undefined;
  9. }
  10. const customTransitionMap: Map<string, AnimateCallback> = new Map();
  11. export class CustomTransition {
  12. static delegate = new CustomTransition();
  13. interactive: boolean = false;
  14. proxy: NavigationTransitionProxy | undefined = undefined;
  15. private animationId: number = 0;
  16. operation: NavigationOperation = NavigationOperation.PUSH
  17. static getInstance() {
  18. return CustomTransition.delegate;
  19. }
  20. /* 注册某个页面的动画回调
  21. * name: 注册页面的唯一id
  22. * startCallback:用来设置动画开始时页面的状态
  23. * endCallback:用来设置动画结束时页面的状态
  24. * onFinish:用来执行动画结束后页面的其他操作
  25. * interactiveCallback: 注册的可交互转场的动效
  26. * timeout:转场结束的超时时间
  27. */
  28. registerNavParam(name: string, startCallback: (operation: boolean, isExit: boolean) => void,
  29. endCallback: (operation: boolean, isExit: boolean) => void,
  30. onFinish: (operation: boolean, isExit: boolean) => void,
  31. interactiveCallback: (operation: NavigationOperation) => void,
  32. timeout: number): void {
  33. if (customTransitionMap.has(name)) {
  34. let param = customTransitionMap.get(name);
  35. if (param != undefined) {
  36. param.start = startCallback;
  37. param.finish = endCallback;
  38. param.timeout = timeout;
  39. param.onFinish = onFinish;
  40. param.interactive = interactiveCallback;
  41. return;
  42. }
  43. }
  44. let params: AnimateCallback = {
  45. timeout: timeout,
  46. start: startCallback,
  47. finish: endCallback,
  48. onFinish: onFinish,
  49. interactive: interactiveCallback
  50. };
  51. customTransitionMap.set(name, params);
  52. }
  53. getAnimationId() {
  54. return Date.now();
  55. }
  56. unRegisterNavParam(name: string): void {
  57. customTransitionMap.delete(name);
  58. }
  59. fireInteractiveAnimation(id: string, operation: NavigationOperation) {
  60. let animation = customTransitionMap.get(id)?.interactive;
  61. if (!animation) {
  62. return;
  63. }
  64. animation(operation);
  65. }
  66. updateProgress(progress: number) {
  67. if (!this.proxy?.updateTransition) {
  68. return;
  69. }
  70. progress = this.operation == NavigationOperation.PUSH ? 1 - progress : progress;
  71. this.proxy?.updateTransition(progress);
  72. }
  73. cancelTransition() {
  74. if (this.proxy?.cancelTransition) {
  75. this.proxy.cancelTransition();
  76. }
  77. }
  78. recoverState() {
  79. if (!this.proxy?.from.navDestinationId || !this.proxy?.to.navDestinationId) {
  80. return;
  81. }
  82. let fromParam = customTransitionMap.get(this.proxy.from.navDestinationId);
  83. if (fromParam?.onFinish) {
  84. fromParam.onFinish(false, false);
  85. }
  86. let toParam = customTransitionMap.get(this.proxy?.to.navDestinationId);
  87. if (toParam?.onFinish) {
  88. toParam.onFinish(true, true);
  89. }
  90. }
  91. finishTransition() {
  92. this.proxy?.finishTransition();
  93. }
  94. finishInteractiveAnimation(rate: number) {
  95. if (this.operation == NavigationOperation.PUSH) {
  96. if (rate > 0.5) {
  97. if (this.proxy?.cancelTransition) {
  98. this.proxy.cancelTransition();
  99. }
  100. } else {
  101. this.proxy?.finishTransition();
  102. }
  103. } else {
  104. if (rate > 0.5) {
  105. this.proxy?.finishTransition();
  106. } else {
  107. if (this.proxy?.cancelTransition) {
  108. this.proxy.cancelTransition();
  109. }
  110. }
  111. }
  112. }
  113. getAnimateParam(name: string): AnimateCallback {
  114. let result: AnimateCallback = {
  115. start: customTransitionMap.get(name)?.start,
  116. finish: customTransitionMap.get(name)?.finish,
  117. timeout: customTransitionMap.get(name)?.timeout,
  118. onFinish: customTransitionMap.get(name)?.onFinish,
  119. interactive: customTransitionMap.get(name)?.interactive,
  120. };
  121. return result;
  122. }
  123. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "pageOne",
  7. "pageSourceFile": "src/main/ets/pages/PageOne.ets",
  8. "buildFunction": "PageOneBuilder",
  9. "data": {
  10. "description": "this is pageOne"
  11. }
  12. },
  13. {
  14. "name": "pageTwo",
  15. "pageSourceFile": "src/main/ets/pages/PageTwo.ets",
  16. "buildFunction": "PageTwoBuilder"
  17. }
  18. ]
  19. }

示例4(Navigation带参返回)

该示例主要演示Navigation通过NavPathStack提供的接口来实现将设置的参数传给上一级页面。

收起
自动换行
深色代码主题
复制
  1. // Index.ets
  2. @Entry
  3. @Component
  4. struct NavigationExample {
  5. pageInfo: NavPathStack = new NavPathStack()
  6. build() {
  7. Navigation(this.pageInfo) {
  8. Column() {
  9. Button('StartTest', { stateEffect: true, type: ButtonType.Capsule })
  10. .width('80%')
  11. .height(40)
  12. .margin(20)
  13. .onClick(() => {
  14. this.pageInfo.pushPath({ name: 'pageOne' }); // 将name指定的NavDestination页面信息入栈。
  15. })
  16. }
  17. }.title('NavIndex')
  18. }
  19. }
收起
自动换行
深色代码主题
复制
  1. // PageOne.ets
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. class TmpClass {
  4. count: number = 10
  5. }
  6. class ParamWithOp {
  7. operation: number = 1
  8. count: number = 10
  9. }
  10. @Builder
  11. export function PageOneBuilder(name: string, param: Object) {
  12. PageOne()
  13. }
  14. @Component
  15. export struct PageOne {
  16. pageInfo: NavPathStack = new NavPathStack();
  17. @State message: string = 'Hello World'
  18. build() {
  19. NavDestination() {
  20. Column() {
  21. Text(this.message)
  22. .width('80%')
  23. .height(50)
  24. .margin(10)
  25. Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
  26. .width('80%')
  27. .height(40)
  28. .margin(10)
  29. .onClick(() => {
  30. this.pageInfo.pushPath({
  31. name: 'pageTwo', param: new ParamWithOp(), onPop: (popInfo: PopInfo) => {
  32. this.message =
  33. '[pushPath]last page is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result);
  34. }
  35. }); // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
  36. })
  37. Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
  38. .width('80%')
  39. .height(40)
  40. .margin(10)
  41. .onClick(() => {
  42. let tmp = new TmpClass()
  43. this.pageInfo.pushPathByName('pageTwo', tmp, (popInfo) => {
  44. this.message =
  45. '[pushPathByName]last page is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result);
  46. }); // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
  47. })
  48. Button('pushDestination', { stateEffect: true, type: ButtonType.Capsule })
  49. .width('80%')
  50. .height(40)
  51. .margin(10)
  52. .onClick(() => {
  53. let tmp = new TmpClass()
  54. // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
  55. this.pageInfo.pushDestination({
  56. name: 'pageTwo', param: new ParamWithOp(), onPop: (popInfo: PopInfo) => {
  57. this.message =
  58. '[pushDestination]last page is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result);
  59. }
  60. }).catch((error: BusinessError) => {
  61. console.error(`[pushDestination]failed, error code = ${error.code}, error.message = ${error.message}.`);
  62. }).then(() => {
  63. console.error('[pushDestination]success.');
  64. });
  65. })
  66. Button('pushDestinationByName', { stateEffect: true, type: ButtonType.Capsule })
  67. .width('80%')
  68. .height(40)
  69. .margin(10)
  70. .onClick(() => {
  71. let tmp = new TmpClass()
  72. // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
  73. this.pageInfo.pushDestinationByName('pageTwo', tmp, (popInfo) => {
  74. this.message = '[pushDestinationByName]last page is: ' + popInfo.info.name + ', result: ' +
  75. JSON.stringify(popInfo.result);
  76. }).catch((error: BusinessError) => {
  77. console.error(`[pushDestinationByName]failed, error code = ${error.code}, error.message = ${error.message}.`);
  78. }).then(() => {
  79. console.error('[pushDestinationByName]success.');
  80. });
  81. })
  82. Button('pushPathWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
  83. .width('80%')
  84. .height(40)
  85. .margin(10)
  86. .onClick(() => {
  87. this.pageInfo.pushPath({ name: 'pageTwo', param: new ParamWithOp() }); // 将name指定的NavDestination页面信息入栈。
  88. })
  89. Button('pushPathByNameWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
  90. .width('80%')
  91. .height(40)
  92. .margin(10)
  93. .onClick(() => {
  94. let tmp = new TmpClass()
  95. this.pageInfo.pushPathByName('pageTwo', tmp); // 将name指定的NavDestination页面信息入栈,传递的数据为param。
  96. })
  97. Button('pushDestinationWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
  98. .width('80%')
  99. .height(40)
  100. .margin(10)
  101. .onClick(() => {
  102. let tmp = new TmpClass()
  103. // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
  104. this.pageInfo.pushDestination({ name: 'pageTwo', param: new ParamWithOp() })
  105. .catch((error: BusinessError) => {
  106. console.error(`[pushDestinationWithoutOnPop]failed, error code = ${error.code}, error.message = ${error.message}.`);
  107. }).then(() => {
  108. console.error('[pushDestinationWithoutOnPop]success.');
  109. });
  110. })
  111. Button('pushDestinationByNameWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
  112. .width('80%')
  113. .height(40)
  114. .margin(10)
  115. .onClick(() => {
  116. let tmp = new TmpClass()
  117. // 将name指定的NavDestination页面信息入栈,传递的数据为param。
  118. this.pageInfo.pushDestinationByName('pageTwo', tmp)
  119. .catch((error: BusinessError) => {
  120. console.error(`[pushDestinationByNameWithoutOnPop]failed, error code = ${error.code}, error.message = ${error.message}.`);
  121. }).then(() => {
  122. console.error('[pushDestinationByNameWithoutOnPop]success.');
  123. });
  124. })
  125. Button('clear', { stateEffect: true, type: ButtonType.Capsule })
  126. .width('80%')
  127. .height(40)
  128. .margin(10)
  129. .onClick(() => {
  130. this.pageInfo.clear(); // 清除栈中所有页面。
  131. })
  132. }.width('100%').height('100%')
  133. }.title('pageOne')
  134. .onBackPressed(() => {
  135. this.pageInfo.pop({ number: 1 }) // 弹出路由栈栈顶元素。
  136. return true
  137. }).onReady((context: NavDestinationContext) => {
  138. this.pageInfo = context.pathStack;
  139. })
  140. }
  141. }
收起
自动换行
深色代码主题
复制
  1. // PageTwo.ets
  2. class resultClass {
  3. constructor(count: number) {
  4. this.count = count;
  5. }
  6. count: number = 10
  7. }
  8. @Builder
  9. export function PageTwoBuilder() {
  10. PageTwo()
  11. }
  12. @Component
  13. export struct PageTwo {
  14. pathStack: NavPathStack = new NavPathStack()
  15. build() {
  16. NavDestination() {
  17. Column() {
  18. Button('pop', { stateEffect: true, type: ButtonType.Capsule })
  19. .width('80%')
  20. .height(40)
  21. .margin(20)
  22. .onClick(() => {
  23. this.pathStack.pop(new resultClass(1)); // 回退到上一个页面,将处理结果传入push的onPop回调中。
  24. })
  25. Button('popToName', { stateEffect: true, type: ButtonType.Capsule })
  26. .width('80%')
  27. .height(40)
  28. .margin(20)
  29. .onClick(() => {
  30. this.pathStack.popToName('pageOne',
  31. new resultClass(11)); // 将第一个名为name的NavDestination页面移到栈顶,将处理结果传入push的onPop回调中。
  32. })
  33. Button('popToIndex', { stateEffect: true, type: ButtonType.Capsule })
  34. .width('80%')
  35. .height(40)
  36. .margin(20)
  37. .onClick(() => {
  38. this.pathStack.popToIndex(0, new resultClass(111)); // 将index指定的NavDestination页面移到栈顶,将处理结果传入push的onPop回调中。
  39. })
  40. Button('popWithoutResult', { stateEffect: true, type: ButtonType.Capsule })
  41. .width('80%')
  42. .height(40)
  43. .margin(20)
  44. .onClick(() => {
  45. this.pathStack.pop();
  46. })
  47. Button('popToNameWithoutResult', { stateEffect: true, type: ButtonType.Capsule })
  48. .width('80%')
  49. .height(40)
  50. .margin(20)
  51. .onClick(() => {
  52. this.pathStack.popToName('pageOne');
  53. })
  54. Button('popToIndexWithoutResult', { stateEffect: true, type: ButtonType.Capsule })
  55. .width('80%')
  56. .height(40)
  57. .margin(20)
  58. .onClick(() => {
  59. this.pathStack.popToIndex(0);
  60. })
  61. }.width('100%').height('100%')
  62. }.title('pageTwo')
  63. .onBackPressed(() => {
  64. this.pathStack.pop(new resultClass(0)); // 回退到上一个页面,将处理结果传入push的onPop回调。
  65. return true;
  66. }).onReady((context: NavDestinationContext) => {
  67. this.pathStack = context.pathStack
  68. })
  69. }
  70. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "pageOne",
  7. "pageSourceFile": "src/main/ets/pages/PageOne.ets",
  8. "buildFunction": "PageOneBuilder",
  9. "data": {
  10. "description": "this is pageOne"
  11. }
  12. },
  13. {
  14. "name": "pageTwo",
  15. "pageSourceFile": "src/main/ets/pages/PageTwo.ets",
  16. "buildFunction": "PageTwoBuilder"
  17. }
  18. ]
  19. }

示例5(设置背景颜色和模糊效果)

该示例主要演示设置Navigation主页的标题栏、工具栏和NavDestination页面的标题栏的背景颜色和背景模糊效果。

收起
自动换行
深色代码主题
复制
  1. let COLOR1: string = "#80004AAF";
  2. let COLOR2: string = "#802787D9";
  3. let BLUR_STYLE_1: BlurStyle = BlurStyle.BACKGROUND_THIN;
  4. let BLUR_STYLE_2: BlurStyle = BlurStyle.BACKGROUND_THICK;
  5. @Component
  6. struct BackComponent {
  7. build() {
  8. Row() {
  9. Column() {
  10. }
  11. .height('100%')
  12. .backgroundColor("#3D9DB4")
  13. .layoutWeight(9)
  14. Column() {
  15. }
  16. .height('100%')
  17. .backgroundColor("#17A98D")
  18. .layoutWeight(9)
  19. Column() {
  20. }
  21. .height('100%')
  22. .backgroundColor("#FFC000")
  23. .layoutWeight(9)
  24. }
  25. .height('100%')
  26. .width('100%')
  27. }
  28. }
  29. @Component
  30. struct ColorAndBlur {
  31. @State useColor1: boolean = true;
  32. @State useBlur1: boolean = true;
  33. build() {
  34. NavDestination() {
  35. Stack({ alignContent: Alignment.Center }) {
  36. BackComponent()
  37. .width('100%')
  38. .height('100%')
  39. Column() {
  40. Stack({ alignContent: Alignment.Center }) {
  41. Button("switch color")
  42. .onClick(() => {
  43. this.useColor1 = !this.useColor1;
  44. })
  45. }
  46. .width('100%')
  47. .layoutWeight(1)
  48. Stack({ alignContent: Alignment.Center }) {
  49. Button("switch blur")
  50. .onClick(() => {
  51. this.useBlur1 = !this.useBlur1;
  52. })
  53. }
  54. .width('100%')
  55. .layoutWeight(1)
  56. }
  57. .width('100%')
  58. .height('100%')
  59. }.width('100%')
  60. .height('100%')
  61. }
  62. .width('100%')
  63. .height('100%')
  64. // 开发者可以设置标题栏的背景颜色和背景模糊效果
  65. .title("switch titlebar color and blur", {
  66. backgroundColor: this.useColor1 ? COLOR1 : COLOR2,
  67. backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2,
  68. barStyle: BarStyle.STACK
  69. })
  70. }
  71. }
  72. @Entry
  73. @Component
  74. struct Index {
  75. private stack: NavPathStack = new NavPathStack();
  76. @State useColor1: boolean = true;
  77. @State useBlur1: boolean = true;
  78. @Builder
  79. PageBuilder(name: string) {
  80. ColorAndBlur()
  81. }
  82. build() {
  83. Navigation(this.stack) {
  84. Stack({ alignContent: Alignment.Center }) {
  85. BackComponent()
  86. .width('100%')
  87. .height('100%')
  88. Column() {
  89. Stack({ alignContent: Alignment.Center }) {
  90. Button("switch color")
  91. .onClick(() => {
  92. this.useColor1 = !this.useColor1;
  93. })
  94. }
  95. .width('100%')
  96. .layoutWeight(1)
  97. Stack({ alignContent: Alignment.Center }) {
  98. Button("switch blur")
  99. .onClick(() => {
  100. this.useBlur1 = !this.useBlur1;
  101. })
  102. }
  103. .width('100%')
  104. .layoutWeight(1)
  105. Stack({ alignContent: Alignment.Center }) {
  106. Button("push page")
  107. .onClick(() => {
  108. this.stack.pushPath({ name: "page" })
  109. })
  110. }
  111. .width('100%')
  112. .layoutWeight(1)
  113. }
  114. .width('100%')
  115. .height('80%')
  116. }.width('100%')
  117. .height('100%')
  118. }
  119. .width('100%')
  120. .height('100%')
  121. .navDestination(this.PageBuilder)
  122. // 开发者可以设置标题栏的背景颜色和背景模糊效果
  123. .title("NavTitle", {
  124. backgroundColor: this.useColor1 ? COLOR1 : COLOR2,
  125. backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2,
  126. barStyle: BarStyle.STACK
  127. })
  128. // 开发者可以设置工具栏的背景颜色和背景模糊效果
  129. .toolbarConfiguration([
  130. { value: "a" },
  131. { value: "b" },
  132. { value: "c" }
  133. ], {
  134. backgroundColor: this.useColor1 ? COLOR1 : COLOR2,
  135. backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2
  136. })
  137. }
  138. }

示例6(嵌套场景下获取外层栈)

该示例主要演示在嵌套Navigation场景下,如何获取父NavPathStack。

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct NavigationExample1 {
  4. @State childNavStack: NavPathStack = new NavPathStack();
  5. build() {
  6. Navigation() {
  7. Stack({ alignContent: Alignment.Center }) {
  8. Navigation(this.childNavStack) {
  9. Button('push Path to parent Navigation', { stateEffect: true, type: ButtonType.Capsule })
  10. .width('80%')
  11. .height(40)
  12. .margin(20)
  13. .onClick(() => {
  14. // 可以获取父NavPathStack
  15. let parentStack = this.childNavStack.getParent();
  16. parentStack?.pushPath({ name: "pageOne" })
  17. })
  18. }
  19. .clip(true)
  20. .backgroundColor(Color.Orange)
  21. .width('80%')
  22. .height('80%')
  23. .title('ChildNavigation')
  24. }
  25. .width('100%')
  26. .height('100%')
  27. }
  28. .backgroundColor(Color.Green)
  29. .width('100%')
  30. .height('100%')
  31. .title('ParentNavigation')
  32. }
  33. }
收起
自动换行
深色代码主题
复制
  1. // PageOne.ets
  2. @Builder
  3. export function PageOneBuilder(name: string) {
  4. NavDestination() {
  5. Text("this is " + name)
  6. }
  7. .title(name)
  8. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "pageOne",
  7. "pageSourceFile": "src/main/ets/pages/PageOne.ets",
  8. "buildFunction": "PageOneBuilder",
  9. "data": {
  10. "description": "this is pageOne"
  11. }
  12. }
  13. ]
  14. }

示例7(通过onReady获取栈)

该示例主要演示如下两点功能:

  1. NavPathStack无需声明为状态变量,也可以实现页面栈操作功能。

  2. NavDestination通过onReady事件能够拿到对应的NavPathInfo和所属的NavPathStack。

收起
自动换行
深色代码主题
复制
  1. class PageParam {
  2. constructor(num_: number) {
  3. this.num = num_;
  4. }
  5. num: number = 0;
  6. }
  7. @Builder
  8. export function PageOneBuilder(name: string, param: Object) {
  9. PageOne()
  10. }
  11. @Component
  12. struct PageOne {
  13. private stack: NavPathStack | null = null;
  14. private name: string = "";
  15. private paramNum: number = 0;
  16. build() {
  17. NavDestination() {
  18. Column() {
  19. Text("NavPathInfo: name: " + this.name + ", paramNum: " + this.paramNum)
  20. Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
  21. .width('80%')
  22. .height(40)
  23. .margin(20)
  24. .onClick(() => {
  25. if (this.stack) {
  26. let p = new PageParam(this.paramNum + 1);
  27. this.stack.pushPath({ name: "pageOne", param: p });
  28. }
  29. })
  30. Button('pop', { stateEffect: true, type: ButtonType.Capsule })
  31. .width('80%')
  32. .height(40)
  33. .margin(20)
  34. .onClick(() => {
  35. this.stack?.pop()
  36. })
  37. }
  38. .width('100%')
  39. .height('100%')
  40. }
  41. .title('pageOne')
  42. .onReady((ctx: NavDestinationContext) => {
  43. // 在NavDestination中能够拿到传来的NavPathInfo和当前所处的NavPathStack
  44. try {
  45. this.name = ctx?.pathInfo?.name;
  46. this.paramNum = (ctx?.pathInfo?.param as PageParam)?.num;
  47. this.stack = ctx.pathStack;
  48. } catch (e) {
  49. console.log(`testTag onReady catch exception: ${JSON.stringify(e)}`)
  50. }
  51. })
  52. }
  53. }
  54. @Entry
  55. @Component
  56. struct NavigationExample2 {
  57. private stack: NavPathStack = new NavPathStack();
  58. build() {
  59. Navigation(this.stack) {
  60. Stack({ alignContent: Alignment.Center }) {
  61. Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
  62. .width('80%')
  63. .height(40)
  64. .margin(20)
  65. .onClick(() => {
  66. let p = new PageParam(1);
  67. this.stack.pushPath({ name: "pageOne", param: p })
  68. })
  69. }
  70. .width('100%')
  71. .height('100%')
  72. }
  73. .width('100%')
  74. .height('100%')
  75. .title('Navigation')
  76. }
  77. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "pageOne",
  7. "pageSourceFile": "src/main/ets/pages/Index.ets",
  8. "buildFunction": "PageOneBuilder",
  9. "data": {
  10. "description": "this is pageOne"
  11. }
  12. }
  13. ]
  14. }

示例8(NavDestination生命周期时序)

该示例演示NavDestination的onAppear,onDisAppear,onShown,onHidden,onWillAppear,onWillDisappear,onWillShow,onWillHide接口的生命周期时序。

收起
自动换行
深色代码主题
复制
  1. @Builder
  2. export function PageOneBuilder(name: string, param: Object) {
  3. PageOneComponent()
  4. }
  5. @Component
  6. struct PageOneComponent {
  7. private stack: NavPathStack | null = null;
  8. @State eventStr: string = "";
  9. build() {
  10. NavDestination() {
  11. Column() {
  12. Text("event: " + this.eventStr)
  13. Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
  14. .width('80%')
  15. .height(40)
  16. .margin(20)
  17. .onClick(() => {
  18. if (this.stack) {
  19. this.stack.pushPath({ name: "pageOne" });
  20. }
  21. })
  22. Button('pop', { stateEffect: true, type: ButtonType.Capsule })
  23. .width('80%')
  24. .height(40)
  25. .margin(20)
  26. .onClick(() => {
  27. this.stack?.pop()
  28. })
  29. }
  30. .width('100%')
  31. .height('100%')
  32. }
  33. .title('pageOne')
  34. .onAppear(() => {
  35. this.eventStr += "<onAppear>";
  36. })
  37. .onDisAppear(() => {
  38. this.eventStr += "<onDisAppear>";
  39. })
  40. .onShown(() => {
  41. this.eventStr += "<onShown>";
  42. })
  43. .onHidden(() => {
  44. this.eventStr += "<onHidden>";
  45. })
  46. .onWillAppear(() => {
  47. this.eventStr += "<onWillAppear>";
  48. })
  49. .onWillDisappear(() => {
  50. this.eventStr += "<onWillDisappear>";
  51. })
  52. .onWillShow(() => {
  53. this.eventStr += "<onWillShow>";
  54. })
  55. .onWillHide(() => {
  56. this.eventStr += "<onWillHide>";
  57. })
  58. // onReady会在onAppear之前调用
  59. .onReady((ctx: NavDestinationContext) => {
  60. try {
  61. this.eventStr += "<onReady>";
  62. this.stack = ctx.pathStack;
  63. } catch (e) {
  64. console.log(`testTag onReady catch exception: ${JSON.stringify(e)}`)
  65. }
  66. })
  67. }
  68. }
  69. @Entry
  70. @Component
  71. struct NavigationExample3 {
  72. private stack: NavPathStack = new NavPathStack();
  73. build() {
  74. Navigation(this.stack) {
  75. Stack({ alignContent: Alignment.Center }) {
  76. Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
  77. .width('80%')
  78. .height(40)
  79. .margin(20)
  80. .onClick(() => {
  81. this.stack.pushPath({ name: "pageOne" })
  82. })
  83. }
  84. .width('100%')
  85. .height('100%')
  86. }
  87. .width('100%')
  88. .height('100%')
  89. .title('Navigation')
  90. }
  91. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "pageOne",
  7. "pageSourceFile": "src/main/ets/pages/Index.ets",
  8. "buildFunction": "PageOneBuilder",
  9. "data": {
  10. "description": "this is pageOne"
  11. }
  12. }
  13. ]
  14. }

示例9(标题栏布局效果)

该示例演示Navigation标题栏STACK布局效果。

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct NavigationExample {
  4. private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  5. private scrollerForScroll: Scroller = new Scroller();
  6. @State barStyle: BarStyle = BarStyle.STANDARD;
  7. build() {
  8. Column() {
  9. Navigation() {
  10. Column() {
  11. Scroll(this.scrollerForScroll) {
  12. Column() {
  13. Image($r('app.media.image_1'))// 设置与标题栏高度一致,以便观察STACK效果
  14. .height(138)
  15. .width('100%')
  16. Button('BarStyle.STANDARD')
  17. .height('50vp')
  18. .onClick(() => {
  19. this.barStyle = BarStyle.STANDARD;
  20. })
  21. Button('BarStyle.STACK')
  22. .height('50vp')
  23. .margin({ top: 12 })
  24. .onClick(() => {
  25. this.barStyle = BarStyle.STACK;
  26. })
  27. ForEach(this.arr, (item: number) => {
  28. ListItem() {
  29. Text('' + item)
  30. .width('100%')
  31. .height(100)
  32. .fontSize(16)
  33. .textAlign(TextAlign.Center)
  34. .borderRadius(10)
  35. .backgroundColor(Color.Orange)
  36. .margin({ top: 12 })
  37. }
  38. }, (item: string) => item)
  39. }
  40. }
  41. }
  42. .width('100%')
  43. .height('100%')
  44. .backgroundColor(0xDCDCDC)
  45. }
  46. .title(
  47. {
  48. main: 'NavTitle',
  49. sub: 'subtitle'
  50. },
  51. {
  52. backgroundBlurStyle: BlurStyle.COMPONENT_THICK,
  53. barStyle: this.barStyle,
  54. }
  55. )
  56. .titleMode(NavigationTitleMode.Free)
  57. .hideTitleBar(false)
  58. }.width('100%').height('100%').backgroundColor('#F1F3F5')
  59. }
  60. }

示例10(定义路由栈派生类)

该示例主要演示如何定义NavPathStack的派生类和派生类在Navigation中的基本用法。

收起
自动换行
深色代码主题
复制
  1. class DerivedNavPathStack extends NavPathStack {
  2. // usr defined property 'id'
  3. id: string = "__default__"
  4. // new function in derived class
  5. setId(id: string) {
  6. this.id = id;
  7. }
  8. // new function in derived class
  9. getInfo(): string {
  10. return "this page used Derived NavPathStack, id: " + this.id
  11. }
  12. // overwrite function of NavPathStack
  13. pushPath(info: NavPathInfo, animated?: boolean): void
  14. pushPath(info: NavPathInfo, options?: NavigationOptions): void
  15. pushPath(info: NavPathInfo, secArg?: boolean | NavigationOptions): void {
  16. console.log('[derive-test] reached DerivedNavPathStack\'s pushPath');
  17. if (typeof secArg === 'boolean') {
  18. super.pushPath(info, secArg);
  19. } else {
  20. super.pushPath(info, secArg);
  21. }
  22. }
  23. // overwrite and overload function of NavPathStack
  24. pop(animated?: boolean | undefined): NavPathInfo | undefined
  25. pop(result: Object, animated?: boolean | undefined): NavPathInfo | undefined
  26. pop(result?: Object, animated?: boolean | undefined): NavPathInfo | undefined {
  27. console.log('[derive-test] reached DerivedNavPathStack\'s pop');
  28. return super.pop(result, animated);
  29. }
  30. // other function of base class...
  31. }
  32. class param {
  33. info: string = "__default_param__";
  34. constructor(info: string) {
  35. this.info = info
  36. }
  37. }
  38. @Entry
  39. @Component
  40. struct Index {
  41. derivedStack: DerivedNavPathStack = new DerivedNavPathStack();
  42. aboutToAppear(): void {
  43. this.derivedStack.setId('origin stack');
  44. }
  45. @Builder
  46. pageMap(name: string) {
  47. PageOne()
  48. }
  49. build() {
  50. Navigation(this.derivedStack) {
  51. Button('to Page One').margin(20).onClick(() => {
  52. this.derivedStack.pushPath({
  53. name: 'pageOne',
  54. param: new param('push pageOne in homePage when stack size: ' + this.derivedStack.size())
  55. });
  56. })
  57. }.navDestination(this.pageMap)
  58. .title('Home Page')
  59. }
  60. }
  61. @Component
  62. struct PageOne {
  63. derivedStack: DerivedNavPathStack = new DerivedNavPathStack();
  64. curStringifyParam: string = "NA";
  65. build() {
  66. NavDestination() {
  67. Column() {
  68. Text(this.derivedStack.getInfo())
  69. .margin(10)
  70. .fontSize(25)
  71. .fontWeight(FontWeight.Bold)
  72. .textAlign(TextAlign.Start)
  73. Text('current page param info:')
  74. .margin(10)
  75. .fontSize(25)
  76. .fontWeight(FontWeight.Bold)
  77. .textAlign(TextAlign.Start)
  78. Text(this.curStringifyParam)
  79. .margin(20)
  80. .fontSize(20)
  81. .textAlign(TextAlign.Start)
  82. }.backgroundColor(Color.Pink)
  83. Button('to Page One').margin(20).onClick(() => {
  84. this.derivedStack.pushPath({
  85. name: 'pageOne',
  86. param: new param('push pageOne in pageOne when stack size: ' + this.derivedStack.size())
  87. });
  88. })
  89. }.title('Page One')
  90. .onReady((context: NavDestinationContext) => {
  91. console.log('[derive-test] reached PageOne\'s onReady');
  92. // get derived stack from navdestinationContext
  93. this.derivedStack = context.pathStack as DerivedNavPathStack;
  94. console.log('[derive-test] -- got derivedStack: ' + this.derivedStack.id);
  95. this.curStringifyParam = JSON.stringify(context.pathInfo.param);
  96. console.log('[derive-test] -- got param: ' + this.curStringifyParam);
  97. })
  98. }
  99. }

示例11(使用Symbol组件)

该示例主要演示Navigation和NavDestination如何使用Symbol组件。

收起
自动换行
深色代码主题
复制
  1. import { SymbolGlyphModifier } from '@kit.ArkUI';
  2. @Entry
  3. @Component
  4. struct NavigationExample {
  5. @Provide('navPathStack') navPathStack: NavPathStack = new NavPathStack();
  6. @State menuItems: Array<NavigationMenuItem> = [
  7. {
  8. value: 'menuItem1',
  9. icon: 'resources/base/media/ic_public_ok.svg' // 图标资源路径
  10. },
  11. {
  12. value: 'menuItem2',
  13. icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
  14. symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_folder_badge_plus')).fontColor([Color.Red, Color.Green])
  15. .renderingStrategy(SymbolRenderingStrategy.MULTIPLE_COLOR),
  16. },
  17. {
  18. value: 'menuItem3',
  19. symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')),
  20. },
  21. ]
  22. @State toolItems: Array<ToolbarItem> = [
  23. {
  24. value: 'toolItem1',
  25. icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
  26. symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')),
  27. status: ToolbarItemStatus.ACTIVE,
  28. activeSymbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_folder_badge_plus')).fontColor([Color.Red,
  29. Color.Green]).renderingStrategy(SymbolRenderingStrategy.MULTIPLE_COLOR),
  30. action: () => {
  31. }
  32. },
  33. {
  34. value: 'toolItem2',
  35. symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_star')),
  36. status: ToolbarItemStatus.ACTIVE,
  37. activeIcon: 'resources/base/media/ic_public_more.svg', // 图标资源路径
  38. action: () => {
  39. }
  40. },
  41. {
  42. value: 'toolItem3',
  43. symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_star')),
  44. status: ToolbarItemStatus.ACTIVE,
  45. activeSymbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')),
  46. action: () => {
  47. }
  48. }
  49. ]
  50. @Builder
  51. myRouter(name: string, param?: Object) {
  52. if (name === 'NavigationMenu') {
  53. NavigationMenu();
  54. }
  55. }
  56. build() {
  57. Navigation(this.navPathStack) {
  58. Column() {
  59. Button('跳转').onClick(() => {
  60. this.navPathStack.pushPathByName('NavigationMenu', null);
  61. })
  62. }
  63. }
  64. .backButtonIcon(new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')))
  65. .titleMode(NavigationTitleMode.Mini)
  66. .menus(this.menuItems)
  67. .toolbarConfiguration(this.toolItems)
  68. .title('一级页面')
  69. .navDestination(this.myRouter)
  70. }
  71. }
  72. @Component
  73. export struct NavigationMenu {
  74. @Consume('navPathStack') navPathStack: NavPathStack;
  75. @State menuItems: Array<NavigationMenuItem> = [
  76. {
  77. value: 'menuItem1',
  78. icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
  79. action: () => {
  80. }
  81. },
  82. {
  83. value: 'menuItem2',
  84. symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_folder_badge_plus')).fontColor([Color.Red, Color.Green])
  85. .renderingStrategy(SymbolRenderingStrategy.MULTIPLE_COLOR),
  86. action: () => {
  87. }
  88. },
  89. {
  90. value: 'menuItem3',
  91. symbolIcon: new SymbolGlyphModifier($r('sys.symbol.repeat_1')),
  92. action: () => {
  93. }
  94. },
  95. ]
  96. build() {
  97. NavDestination() {
  98. Row() {
  99. Column() {
  100. }
  101. .width('100%')
  102. }
  103. .height('100%')
  104. }
  105. .hideTitleBar(false)
  106. .title('NavDestination title')
  107. .backgroundColor($r('sys.color.ohos_id_color_titlebar_sub_bg'))
  108. .backButtonIcon(new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Blue]))
  109. .menus(this.menuItems)
  110. }
  111. }

示例12(设置自定义标题栏边距)

该示例主要演示Navigation和NavDestination如何设置自定义标题栏边距,如何通过TextModifier修改主副标题文本样式。

收起
自动换行
深色代码主题
复制
  1. import { LengthMetrics } from '@kit.ArkUI';
  2. import { TextModifier } from '@ohos.arkui.modifier';
  3. class MainTitleTextModfier extends TextModifier {
  4. useStyle1: boolean = true;
  5. applyNormalAttribute(instance: TextModifier): void {
  6. if (this.useStyle1) {
  7. console.log(`testTag mainTitle use style1`);
  8. instance.fontColor('#FFFFC000')
  9. instance.fontSize(35)
  10. instance.fontWeight(FontWeight.Bolder)
  11. instance.fontStyle(FontStyle.Normal)
  12. instance.textShadow({ radius: 5, offsetX: 9 })
  13. } else {
  14. console.log(`testTag mainTitle use style2`);
  15. instance.fontColor('#FF23A98D')
  16. instance.fontSize(20)
  17. instance.heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
  18. instance.fontWeight(FontWeight.Lighter)
  19. instance.fontStyle(FontStyle.Italic)
  20. instance.textShadow({ radius: 3, offsetX: 3 })
  21. }
  22. }
  23. }
  24. class SubTitleTextModfier extends TextModifier {
  25. useStyle1: boolean = true;
  26. applyNormalAttribute(instance: TextModifier): void {
  27. if (this.useStyle1) {
  28. console.log(`testTag subTitle use style1`);
  29. instance.fontColor('#FFFFC000')
  30. instance.fontSize(15)
  31. instance.fontWeight(FontWeight.Bolder)
  32. instance.fontStyle(FontStyle.Normal)
  33. instance.textShadow({ radius: 5, offsetX: 9 })
  34. } else {
  35. console.log(`testTag subTitle use style2`);
  36. instance.fontColor('#FF23A98D')
  37. instance.fontSize(10)
  38. instance.fontWeight(FontWeight.Lighter)
  39. instance.fontStyle(FontStyle.Italic)
  40. instance.textShadow({ radius: 3, offsetX: 3 })
  41. }
  42. }
  43. }
  44. @Entry
  45. @Component
  46. struct NavigationExample {
  47. private navPathStack: NavPathStack = new NavPathStack();
  48. // 初始化标题栏起始端内间距
  49. @State paddingStart: LengthMetrics = LengthMetrics.vp(0);
  50. // 初始化标题栏结束端内间距
  51. @State paddingEnd: LengthMetrics = LengthMetrics.vp(0);
  52. // 主标题样式修改器
  53. @State mainTitleModifier: MainTitleTextModfier = new MainTitleTextModfier();
  54. // 副标题样式修改器
  55. @State subTitleModifier: SubTitleTextModfier = new SubTitleTextModfier();
  56. @State applyModifier: boolean = false;
  57. @State useStyle1: boolean = true;
  58. @Builder
  59. myRouter(name: string, param?: Object) {
  60. if (name === 'NavDestinationExample') {
  61. NavDestinationExample();
  62. }
  63. }
  64. build() {
  65. Navigation(this.navPathStack) {
  66. Column() {
  67. // 标题栏内间距切换
  68. Button('apply padding 32vp')
  69. .onClick(() => {
  70. this.paddingStart = LengthMetrics.vp(32);
  71. this.paddingEnd = LengthMetrics.vp(32);
  72. })
  73. .margin({ top: 70 })
  74. .width(180)
  75. Button('apply padding 20vp')
  76. .onClick(() => {
  77. this.paddingStart = LengthMetrics.vp(20);
  78. this.paddingEnd = LengthMetrics.vp(20);
  79. })
  80. .margin({ top: 40 })
  81. .width(180)
  82. Button('pushPage')
  83. .onClick(() => {
  84. this.navPathStack.pushPath({ name: 'NavDestinationExample' })
  85. })
  86. .margin({ top: 40 })
  87. .width(180)
  88. Row() {
  89. Text(`apply Modifier`)
  90. Toggle({ isOn: this.applyModifier, type: ToggleType.Switch }).onChange((isOn: boolean) => {
  91. this.applyModifier = isOn;
  92. })
  93. }
  94. .padding({ top: 95, left: 5, right: 5 })
  95. .width(180)
  96. .justifyContent(FlexAlign.SpaceBetween)
  97. Row() {
  98. Text(`use Style1`)
  99. Toggle({ isOn: this.useStyle1, type: ToggleType.Switch }).onChange((isOn: boolean) => {
  100. this.mainTitleModifier.useStyle1 = isOn;
  101. this.subTitleModifier.useStyle1 = isOn;
  102. this.useStyle1 = isOn;
  103. })
  104. }
  105. .padding({ top: 40, left: 5, right: 5 })
  106. .width(180)
  107. .justifyContent(FlexAlign.SpaceBetween)
  108. }
  109. .width('100%')
  110. .height('100%')
  111. }
  112. .titleMode(NavigationTitleMode.Full)
  113. .title(
  114. { main: "Title", sub: "subTitle" },
  115. this.applyModifier ?
  116. {
  117. paddingStart: this.paddingStart,
  118. paddingEnd: this.paddingEnd,
  119. mainTitleModifier: this.mainTitleModifier,
  120. subTitleModifier: this.subTitleModifier,
  121. } : {
  122. paddingStart: this.paddingStart,
  123. paddingEnd: this.paddingEnd
  124. })
  125. .navDestination(this.myRouter)
  126. }
  127. }
  128. @Component
  129. export struct NavDestinationExample {
  130. @State menuItems: Array<NavigationMenuItem> = [
  131. {
  132. value: 'menuItem1',
  133. icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
  134. action: () => {
  135. }
  136. }
  137. ]
  138. @State paddingStart: LengthMetrics = LengthMetrics.vp(0);
  139. @State paddingEnd: LengthMetrics = LengthMetrics.vp(0);
  140. // 主标题样式修改器
  141. @State mainTitleModifier: MainTitleTextModfier = new MainTitleTextModfier();
  142. // 副标题样式修改器
  143. @State subTitleModifier: SubTitleTextModfier = new SubTitleTextModfier();
  144. @State applyModifier: boolean = false;
  145. @State useStyle1: boolean = true;
  146. build() {
  147. NavDestination() {
  148. Column() {
  149. // 标题栏内间距切换
  150. Button('apply padding 32vp')
  151. .onClick(() => {
  152. this.paddingStart = LengthMetrics.vp(32);
  153. this.paddingEnd = LengthMetrics.vp(32);
  154. })
  155. .margin({ top: 150 })
  156. .width(180)
  157. Button('apply padding 20vp')
  158. .onClick(() => {
  159. this.paddingStart = LengthMetrics.vp(20);
  160. this.paddingEnd = LengthMetrics.vp(20);
  161. })
  162. .margin({ top: 40 })
  163. .width(180)
  164. Row() {
  165. Text(`apply Modifier`)
  166. Toggle({ isOn: this.applyModifier, type: ToggleType.Switch }).onChange((isOn: boolean) => {
  167. this.applyModifier = isOn;
  168. })
  169. }
  170. .padding({ top: 95, left: 5, right: 5 })
  171. .width(180)
  172. .justifyContent(FlexAlign.SpaceBetween)
  173. Row() {
  174. Text(`use Style1`)
  175. Toggle({ isOn: this.useStyle1, type: ToggleType.Switch }).onChange((isOn: boolean) => {
  176. this.mainTitleModifier.useStyle1 = isOn;
  177. this.subTitleModifier.useStyle1 = isOn;
  178. this.useStyle1 = isOn;
  179. })
  180. }
  181. .padding({ top: 40, left: 5, right: 5 })
  182. .width(180)
  183. .justifyContent(FlexAlign.SpaceBetween)
  184. }
  185. .width('100%')
  186. .height('90%')
  187. }
  188. .hideTitleBar(false)
  189. .title(
  190. { main: "Title", sub: "subTitle" },
  191. this.applyModifier ?
  192. {
  193. paddingStart: this.paddingStart,
  194. paddingEnd: this.paddingEnd,
  195. mainTitleModifier: this.mainTitleModifier,
  196. subTitleModifier: this.subTitleModifier,
  197. } : {
  198. paddingStart: this.paddingStart,
  199. paddingEnd: this.paddingEnd
  200. })
  201. .menus(this.menuItems)
  202. }
  203. }

示例13(自定义转场动画)

该示例主要实现Navigation简单的自定义转场动画。

收起
自动换行
深色代码主题
复制
  1. // Index.ets
  2. import { AnimateCallback, CustomTransition } from './CustomTransitionUtils'
  3. @Entry
  4. @Component
  5. struct NavigationCustomTransitionExample {
  6. pageInfos: NavPathStack = new NavPathStack();
  7. aboutToAppear() {
  8. this.pageInfos.pushPath({ name: 'PageOne' }, false);
  9. }
  10. build() {
  11. Navigation(this.pageInfos) {
  12. }
  13. .hideNavBar(true)
  14. .customNavContentTransition((from: NavContentInfo, to: NavContentInfo, operation: NavigationOperation) => {
  15. // 首页不进行自定义动画
  16. if (from.index === -1 || to.index === -1) {
  17. return undefined;
  18. }
  19. let customAnimation: NavigationAnimatedTransition = {
  20. timeout: 2000,
  21. // 转场开始时系统调用该方法,并传入转场上下文代理对象
  22. transition: (transitionProxy: NavigationTransitionProxy) => {
  23. if (!from.navDestinationId || !to.navDestinationId) {
  24. return;
  25. }
  26. // 从封装类CustomTransition中根据子页面的序列获取对应的转场动画回调
  27. let fromParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(from.navDestinationId);
  28. let toParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(to.navDestinationId);
  29. // Push动画
  30. if (operation == NavigationOperation.PUSH) {
  31. if (fromParam.start && toParam.start) {
  32. // 设置Push转场的两个页面的动画起点
  33. fromParam.start(true, true);
  34. toParam.start(true, false);
  35. }
  36. animateTo({
  37. duration: 500, curve: Curve.Friction, onFinish: () => {
  38. // 动画结束后需要手动调用finishTransition,否则在timeout时间后由系统调用
  39. transitionProxy.finishTransition();
  40. }
  41. }, () => {
  42. if (fromParam.finish && toParam.finish) {
  43. // 设置Push转场的两个页面的动画终点
  44. fromParam.finish(true, true);
  45. toParam.finish(true, false);
  46. }
  47. })
  48. } else if (operation == NavigationOperation.POP) {
  49. // Pop动画
  50. if (fromParam.start && toParam.start) {
  51. // 设置Pop转场的两个页面的动画起点
  52. fromParam.start(false, true);
  53. toParam.start(false, false);
  54. }
  55. animateTo({
  56. duration: 500, curve: Curve.Friction, onFinish: () => {
  57. // 动画结束后需要手动调用finishTransition,否则在timeout时间后由系统调用
  58. transitionProxy.finishTransition();
  59. }
  60. }, () => {
  61. if (fromParam.finish && toParam.finish) {
  62. // 设置Pop转场的两个页面的动画终点
  63. fromParam.finish(false, true);
  64. toParam.finish(false, false);
  65. }
  66. })
  67. } else {
  68. // Replace不做动画
  69. }
  70. }
  71. };
  72. return customAnimation;
  73. })
  74. }
  75. }
  76. // PageOne
  77. @Builder
  78. export function PageOneBuilder() {
  79. PageContainer({ title: "PageOne" })
  80. }
  81. // PageTwo
  82. @Builder
  83. export function PageTwoBuilder() {
  84. PageContainer({ title: "PageTwo" })
  85. }
  86. @Component
  87. export struct PageContainer {
  88. pageInfos: NavPathStack = new NavPathStack();
  89. @State translateY: string = '0';
  90. pageId: string = '';
  91. title: string = ''
  92. registerCallback() {
  93. CustomTransition.getInstance().registerNavParam(this.pageId,
  94. // 设置转场动画起点,根据不同的转场类型分别设置
  95. (isPush: boolean, isExit: boolean) => {
  96. if (isPush) {
  97. if (isExit) {
  98. this.translateY = '0';
  99. } else {
  100. this.translateY = '100%';
  101. }
  102. } else {
  103. if (isExit) {
  104. this.translateY = '0';
  105. } else {
  106. this.translateY = '0';
  107. }
  108. }
  109. },
  110. // 设置转场动画终点,根据不同的转场类型分别设置
  111. (isPush: boolean, isExit: boolean) => {
  112. if (isPush) {
  113. if (isExit) {
  114. this.translateY = '0';
  115. } else {
  116. this.translateY = '0';
  117. }
  118. } else {
  119. if (isExit) {
  120. this.translateY = '100%';
  121. } else {
  122. this.translateY = '0';
  123. }
  124. }
  125. });
  126. }
  127. build() {
  128. NavDestination() {
  129. Column() {
  130. Button('push next page', { stateEffect: true, type: ButtonType.Capsule })
  131. .width('80%')
  132. .height(40)
  133. .margin(20)
  134. .onClick(() => {
  135. this.pageInfos.pushPath({ name: this.title == 'PageOne' ? "PageTwo" : "PageOne" })
  136. })
  137. }
  138. .size({ width: '100%', height: '100%' })
  139. }
  140. .title(this.title)
  141. .onDisAppear(() => {
  142. // 页面销毁时解注册自定义转场动画参数
  143. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
  144. })
  145. .onReady((context: NavDestinationContext) => {
  146. this.pageInfos = context.pathStack;
  147. if (context.navDestinationId) {
  148. this.pageId = context.navDestinationId;
  149. // 页面创建时注册自定义转场动画参数
  150. this.registerCallback();
  151. }
  152. })
  153. .translate({ y: this.translateY })
  154. .backgroundColor(this.title == 'PageOne' ? '#F1F3F5' : '#ff11dee5')
  155. }
  156. }
收起
自动换行
深色代码主题
复制
  1. // CustomNavigationUtils.ts 工具类,用来管理所有页面的自定义动画参数注册和获取等
  2. // 自定义接口,用来保存某个页面相关的转场动画回调和参数
  3. export interface AnimateCallback {
  4. start: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined;
  5. finish: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined
  6. }
  7. const customTransitionMap: Map<string, AnimateCallback> = new Map();
  8. export class CustomTransition {
  9. static delegate = new CustomTransition();
  10. static getInstance() {
  11. return CustomTransition.delegate;
  12. }
  13. /* 注册某个页面的动画回调
  14. * name: 注册页面的唯一id
  15. * startCallback:用来设置动画开始时页面的状态
  16. * endCallback:用来设置动画结束时页面的状态
  17. */
  18. registerNavParam(name: string, startCallback: (isPush: boolean, isExit: boolean) => void,
  19. endCallback: (isPush: boolean, isExit: boolean) => void): void {
  20. if (customTransitionMap.has(name)) {
  21. let param = customTransitionMap.get(name);
  22. if (param != undefined) {
  23. param.start = startCallback;
  24. param.finish = endCallback;
  25. return;
  26. }
  27. }
  28. let params: AnimateCallback = { start: startCallback, finish: endCallback };
  29. customTransitionMap.set(name, params);
  30. }
  31. unRegisterNavParam(name: string): void {
  32. customTransitionMap.delete(name);
  33. }
  34. getAnimateParam(name: string): AnimateCallback {
  35. let result: AnimateCallback = {
  36. start: customTransitionMap.get(name)?.start,
  37. finish: customTransitionMap.get(name)?.finish
  38. };
  39. return result;
  40. }
  41. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "PageOne",
  7. "pageSourceFile": "src/main/ets/pages/Index.ets",
  8. "buildFunction": "PageOneBuilder",
  9. "data": {
  10. "description": "this is pageOne"
  11. }
  12. },
  13. {
  14. "name": "PageTwo",
  15. "pageSourceFile": "src/main/ets/pages/Index.ets",
  16. "buildFunction": "PageTwoBuilder"
  17. }
  18. ]
  19. }

在 API参考 中进行搜索
请输入您想要搜索的关键词