鸿蒙5.0开发进阶:UI框架-ArkTS组件(Navigation)

鸿蒙(HarmonyOS)组件化路由框架——Navigation的路由管理 Navigation由NavDestination组件组成页面路由,在实现过程中NavDestination组件会被封装在一个自定义组件中,从而作为一个页面被路由栈使用。当前支持的生命周期函数:aboutToAppear、onReady、onAppear、onShow、onHide、onDisappear、aboutToDisappear 、onWillAppear、onWillDisappear。 阅读详情

往期鸿蒙全套实战文章必看:(文中附带全栈鸿蒙学习资料)


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

参数:

参数名类型必填说明
pathInfosNavPathStack是路由栈信息。

属性

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

title

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

设置页面标题。

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

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

参数:

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

subTitle(deprecated)

subTitle(value: string)

设置页面副标题。

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

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

参数:

参数名类型必填说明
valuestring是页面副标题。

menus(value: Array<NavigationMenuItem> | CustomBuilder)

说明

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

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

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

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

参数:

参数名类型必填说明
valueArray<NavigationMenuItem> | CustomBuilder是页面右上角菜单。

titleMode

titleMode(value: NavigationTitleMode)

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

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

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

参数:

参数名类型必填说明
valueNavigationTitleMode是

页面标题栏显示模式。

默认值:NavigationTitleMode.Free

toolBar(deprecated)

toolBar(value: object | CustomBuilder)

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

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

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

参数:

参数名类型必填说明
valueobject | CustomBuilder是工具栏内容。

object类型说明:

名称类型必填说明
valuestring是工具栏单个选项的显示文本。
iconstring否工具栏单个选项的图标资源路径。
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

参数:

参数名类型必填说明
valueArray<ToolbarItem> | CustomBuilder是

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

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

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

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

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

optionsNavigationToolbarOptions11+否工具栏选项。

hideToolBar

hideToolBar(value: boolean)

设置是否隐藏工具栏。

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

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

参数:

参数名类型必填说明
valueboolean是

是否隐藏工具栏。

默认值:false

true: 隐藏工具栏。

false: 显示工具栏。

hideTitleBar

hideTitleBar(value: boolean)

设置是否隐藏标题栏。

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

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

参数:

参数名类型必填说明
valueboolean是

是否隐藏标题栏。

默认值:false

true: 隐藏标题栏。

false: 显示标题栏。

hideBackButton

hideBackButton(value: boolean)

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

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

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

参数:

参数名类型必填说明
valueboolean是

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

默认值:false

true: 隐藏返回键。

false: 显示返回键。

navBarWidth(value: Length)

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

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

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

参数:

参数名类型必填说明
valueLength是

导航栏宽度。

默认值:240

单位:vp

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

navBarPosition(value: NavBarPosition)

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

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

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

参数:

参数名类型必填说明
valueNavBarPosition是

导航栏位置。

默认值:NavBarPosition.Start

mode9+

mode(value: NavigationMode)

设置导航栏的显示模式。支持Stack、Split与Auto模式。

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

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

参数:

参数名类型必填说明
valueNavigationMode是

导航栏的显示模式。

默认值:NavigationMode.Auto

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

backButtonIcon9+

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

说明

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

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

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

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

参数:

参数名类型必填说明
valuestring | 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

参数:

参数名类型必填说明
valueboolean是

是否隐藏导航栏。

默认值: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

参数:

参数名类型必填说明
valueDimension是

导航栏内容区最小宽度。

默认值: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

参数:

参数名类型必填说明
typesArray <LayoutSafeAreaType>否

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

默认值:

[LayoutSafeAreaType.SYSTEM]

edgesArray <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

参数:

参数名类型必填说明
styleOptional<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设置的状态栏不生效。

事件

onTitleModeChange

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

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

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

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

参数:

参数名类型必填说明
titleModeNavigationTitleMode是标题模式。

onNavBarStateChange9+

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

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

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

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

参数:

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

onNavigationModeChange11+

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

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

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

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

参数:

参数名类型必填说明
modeNavigationMode是

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

参数:

参数名类型必填说明
fromNavContentInfo是退场Destination的页面。
toNavContentInfo是进场Destination的页面。
operationNavigationOperation是转场类型。

返回值:

类型说明
NavigationAnimatedTransition | undefined

自定义转场动画协议。

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

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

说明

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

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

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

pushPath10+

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

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

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

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

参数:

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

pushPath12+

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

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

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

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

参数:

参数名类型必填说明
infoNavPathInfo是NavDestination页面的信息。
optionsNavigationOptions否页面栈操作选项。

pushPathByName10+

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

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

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

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

参数:

参数名类型必填说明
namestring是NavDestination页面名称。
paramunknown是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

参数:

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

pushDestination11+

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

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

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

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

参数:

参数名类型必填说明
infoNavPathInfo是NavDestination页面的信息。
animatedboolean否是否支持转场动画,默认值:true。

返回值:

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

错误码:

以下错误码的详细介绍。

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

pushDestination12+

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

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

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

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

参数:

参数名类型必填说明
infoNavPathInfo是NavDestination页面的信息。
optionsNavigationOptions否页面栈操作选项。

返回值:

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

错误码:

以下错误码的详细介绍。

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

pushDestinationByName11+

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

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

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

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

参数:

参数名类型必填说明
namestring是NavDestination页面名称。
paramObject是NavDestination页面详细参数。
animatedboolean否是否支持转场动画,默认值:true。

返回值:

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

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100005Builder function not registered.
100006NavDestination 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

参数:

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

返回值:

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

错误码:

以下错误码的详细介绍。

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

replacePath11+

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

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

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

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

参数:

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

replacePath12+

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

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

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

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

参数:

参数名类型必填说明
infoNavPathInfo是新栈顶页面参数信息。
optionsNavigationOptions否页面栈操作选项。

replacePathByName11+

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

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

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

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

参数:

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

removeByIndexes11+

removeByIndexes(indexes: Array<number>): number

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

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

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

参数:

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

返回值:

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

removeByName11+

removeByName(name: string): number

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

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

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

参数:

参数名类型必填说明
namestring是删除的NavDestination页面的名字。

返回值:

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

removeByNavDestinationId12+

removeByNavDestinationId(navDestinationId: string): boolean

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

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

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

参数:

参数名类型必填说明
navDestinationIdstring是删除的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

参数:

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

返回值:

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

popToName10+

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

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

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

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

参数:

参数名类型必填说明
namestring是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

参数:

参数名类型必填说明
namestring是NavDestination页面名称。
resultObject是页面自定义处理结果。不支持boolean类型。
animatedboolean否是否支持转场动画,默认值:true。

返回值:

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

popToIndex10+

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

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

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

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

参数:

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

popToIndex11+

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

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

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

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

参数:

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

moveToTop10+

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

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

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

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

参数:

参数名类型必填说明
namestring是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

参数:

参数名类型必填说明
indexnumber是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

参数:

参数名类型必填说明
indexnumber是NavDestination页面的位置索引。

返回值:

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

getParamByName10+

getParamByName(name: string): Array<unknown>

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

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

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

参数:

参数名类型必填说明
namestring是NavDestination页面名称。

返回值:

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

getIndexByName10+

getIndexByName(name: string): Array<number>

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

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

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

参数:

参数名类型必填说明
namestring是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

参数:

参数名类型必填说明
valueboolean否是否关闭转场动画,默认值: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

参数:

参数名类型必填说明
interceptionNavigationInterception是设置Navigation跳转拦截对象。

路由页面信息。

constructor

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

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

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

参数名类型必填说明
namestring是NavDestination页面名称。
paramunknown是NavDestination页面详细参数。
onPop11+Callback<PopInfo>否NavDestination页面触发pop时返回的回调。仅pop中设置result参数后触发。
isEntry12+boolean否

标记NavDestination是否为入口页面。

默认值:false

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

说明:

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

属性

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

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

名称类型必填说明
namestring是NavDestination页面名称。
paramunknown否NavDestination页面详细参数。
onPop11+Callback<PopInfo>否NavDestination页面触发pop时返回的回调。仅pop中设置result参数后触发。
isEntry12+boolean否

标记NavDestination是否为入口页面。

默认值:false

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

说明:

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

PopInfo11+

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

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

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

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

跳转Destination信息。

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

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

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

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

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

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

名称类型必填说明
timeoutnumber否

动画超时结束时间。

单位: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

名称类型必填说明
fromNavContentInfo是退场页面信息。
toNavContentInfo是进场页面信息。
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

参数:

参数名类型必填描述
progressnumber是设置交互转场动画进度百分比。取值范围 0-1。

Navigation跳转拦截对象。

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

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

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

InterceptionShowCallback12+

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

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

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

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

参数名类型必填说明
fromNavDestinationContext |NavBar是页面跳转之前的栈顶页面信息。参数值为navBar,则表示跳转前的页面为Navigation首页。
toNavDestinationContext |NavBar是页面跳转之后的栈顶页面信息。参数值为navBar,则表示跳转的目标页面为Navigation首页。
operationNavigationOperation是当前页面跳转类型。
isAnimatedboolean是页面跳转是否有动画。

InterceptionModeCallback12+

type InterceptionModeCallback = (mode: NavigationMode) => void

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

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

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

参数名类型必填说明
modeNavigationMode是导航栏的显示模式。

type NavBar = 'navBar'

Navigation首页名字。

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

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

类型说明
"navBar"Navigation首页。

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

名称类型必填说明
valuestring是

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

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

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

iconstring否

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

元服务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

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

工具栏单个选项的状态。

默认值:ToolbarItemStatus.NORMAL

activeIconResourceStr否工具栏单个选项处于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

名称类型必填说明
mainstring是设置主标题。
substring是设置副标题。

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

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

名称类型必填说明
builderCustomBuilder是设置标题栏内容。
heightTitleHeight | 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+枚举说明

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

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

名称描述
STANDARD标题栏与内容区采用上下布局。
STACK标题栏与内容区采用层叠布局,标题栏布局在内容区上层。

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

名称类型必填说明
backgroundColorResourceColor否

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

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

backgroundBlurStyleBlurStyle否

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

元服务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开始,该接口支持在元服务中使用。

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

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

名称类型必填说明
backgroundColorResourceColor否工具栏背景颜色,不设置时为系统默认颜色。
backgroundBlurStyleBlurStyle否工具栏背景模糊样式,不设置时关闭背景模糊效果。

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

名称类型必填说明
launchModeLaunchMode否

页面栈的操作模式。

默认值:LaunchMode.STANDARD

animatedboolean否

是否支持转场动画。

默认值:true。

示例

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

示例1(Navigation页面布局)

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

// xxx.ets
class A {
  text: string = ''
  num: number = 0
}

@Entry
@Component
struct NavigationExample {
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  @State currentIndex: number = 0

  @Builder
  NavigationTitle() {
    Column() {
      Text('Title')
        .fontColor('#182431')
        .fontSize(30)
        .lineHeight(41)
        .fontWeight(700)
      Text('subtitle')
        .fontColor('#182431')
        .fontSize(14)
        .lineHeight(19)
        .opacity(0.4)
        .margin({ top: 2, bottom: 20 })
    }.alignItems(HorizontalAlign.Start)
  }

  @Builder
  NavigationMenus() {
    Row() {
      Image('resources/base/media/ic_public_add.svg')
        .width(24)
        .height(24)
      Image('resources/base/media/ic_public_add.svg')
        .width(24)
        .height(24)
        .margin({ left: 24 })
      Image('common/ic_public_more.svg')
        .width(24)
        .height(24)
        .margin({ left: 24 })
    }
  }

  build() {
    Column() {
      Navigation() {
        TextInput({ placeholder: 'search...' })
          .width('90%')
          .height(40)
          .backgroundColor('#FFFFFF')
          .margin({ top: 8 })

        List({ space: 12, initialIndex: 0 }) {
          ForEach(this.arr, (item: number) => {
            ListItem() {
              Text('' + item)
                .width('90%')
                .height(72)
                .backgroundColor('#FFFFFF')
                .borderRadius(24)
                .fontSize(16)
                .fontWeight(500)
                .textAlign(TextAlign.Center)
            }
          }, (item: number) => item.toString())
        }
        .height(324)
        .width('100%')
        .margin({ top: 12, left: '10%' })
      }
      .title(this.NavigationTitle)
      .menus(this.NavigationMenus)
      .titleMode(NavigationTitleMode.Full)
      .toolbarConfiguration([
        {
          value: $r("app.string.navigation_toolbar_add"),
          icon: $r("app.media.ic_public_highlightsed")
        },
        {
          value: $r("app.string.navigation_toolbar_app"),
          icon: $r("app.media.ic_public_highlights")
        },
        {
          value: $r("app.string.navigation_toolbar_collect"),
          icon: $r("app.media.ic_public_highlights")
        }
      ])
      .hideTitleBar(false)
      .hideToolBar(false)
      .onTitleModeChange((titleModel: NavigationTitleMode) => {
        console.info('titleMode' + titleModel)
      })
    }.width('100%').height('100%').backgroundColor('#F1F3F5')
  }
}

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

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

// Index.ets

@Entry
@Component
struct NavigationExample {
  pageInfos: NavPathStack = new NavPathStack()
  isUseInterception: boolean = false;

  registerInterception() {
    this.pageInfos.setInterception({
      // 页面跳转前拦截,允许操作栈,在当前跳转中生效。
      willShow: (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar",
        operation: NavigationOperation, animated: boolean) => {
        if (!this.isUseInterception) {
          return;
        }
        if (typeof to === "string") {
          console.log("target page is navigation home");
          return;
        }
        // 重定向目标页面,更改为pageTwo页面到pageOne页面。
        let target: NavDestinationContext = to as NavDestinationContext;
        if (target.pathInfo.name === 'pageTwo') {
          target.pathStack.pop();
          target.pathStack.pushPathByName('pageOne', null);
        }
      },
      // 页面跳转后回调,在该回调中操作栈在下一次跳转中刷新。
      didShow: (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar",
        operation: NavigationOperation, isAnimated: boolean) => {
        if (!this.isUseInterception) {
          return;
        }
        if (typeof from === "string") {
          console.log("current transition is from navigation home");
        } else {
          console.log(`current transition is from  ${(from as NavDestinationContext).pathInfo.name}`)
        }
        if (typeof to === "string") {
          console.log("current transition to is navBar");
        } else {
          console.log(`current transition is to ${(to as NavDestinationContext).pathInfo.name}`);
        }
      },
      // Navigation单双栏显示状态发生变更时触发该回调。
      modeChange: (mode: NavigationMode) => {
        if (!this.isUseInterception) {
          return;
        }
        console.log(`current navigation mode is ${mode}`);
      }
    })
  }

  build() {
    Navigation(this.pageInfos) {
      Column() {
        Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfos.pushPath({ name: 'pageOne' }) //将name指定的NavDestination页面信息入栈
          })
        Button('use interception', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.isUseInterception = !this.isUseInterception;
            if (this.isUseInterception) {
              this.registerInterception();
            } else {
              this.pageInfos.setInterception(undefined);
            }
          })
      }
    }.title('NavIndex')
  }
}
// PageOne.ets
class TmpClass {
  count: number = 10
}

@Builder
export function PageOneBuilder(name: string, param: Object) {
  PageOne()
}

@Component
export struct PageOne {
  pageInfos: NavPathStack = new NavPathStack()

  build() {
    NavDestination() {
      Column() {
        Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            let tmp = new TmpClass()
            this.pageInfos.pushPathByName('pageTwo', tmp) //将name指定的NavDestination页面信息入栈,传递的数据为param
          })
        Button('singletonLaunchMode', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfos.pushPath({ name: 'pageOne' },
              { launchMode: LaunchMode.MOVE_TO_TOP_SINGLETON }) //从栈底向栈顶查找,如果指定的名称已经存在,则将对应的NavDestination页面移到栈顶
          })
        Button('popToname', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfos.popToName('pageTwo') //回退路由栈到第一个名为name的NavDestination页面
            console.log('popToName' + JSON.stringify(this.pageInfos),
              '返回值' + JSON.stringify(this.pageInfos.popToName('pageTwo')))
          })
        Button('popToIndex', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfos.popToIndex(1) // 回退路由栈到index指定的NavDestination页面
            console.log('popToIndex' + JSON.stringify(this.pageInfos))
          })
        Button('moveToTop', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfos.moveToTop('pageTwo') // 将第一个名为name的NavDestination页面移到栈顶
            console.log('moveToTop' + JSON.stringify(this.pageInfos),
              '返回值' + JSON.stringify(this.pageInfos.moveToTop('pageTwo')))
          })
        Button('moveIndexToTop', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfos.moveIndexToTop(1) // 将index指定的NavDestination页面移到栈顶
            console.log('moveIndexToTop' + JSON.stringify(this.pageInfos))
          })
        Button('clear', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfos.clear() //清除栈中所有页面
          })
        Button('get', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            console.log('-------------------')
            console.log('获取栈中所有NavDestination页面的名称', JSON.stringify(this.pageInfos.getAllPathName()))
            console.log('获取index指定的NavDestination页面的参数信息',
              JSON.stringify(this.pageInfos.getParamByIndex(1)))
            console.log('获取全部名为name的NavDestination页面的参数信息',
              JSON.stringify(this.pageInfos.getParamByName('pageTwo')))
            console.log('获取全部名为name的NavDestination页面的位置索引',
              JSON.stringify(this.pageInfos.getIndexByName('pageOne')))
            console.log('获取栈大小', JSON.stringify(this.pageInfos.size()))
          })
      }.width('100%').height('100%')
    }.title('pageOne')
    .onBackPressed(() => {
      const popDestinationInfo = this.pageInfos.pop() // 弹出路由栈栈顶元素
      console.log('pop' + '返回值' + JSON.stringify(popDestinationInfo))
      return true
    }).onReady((context: NavDestinationContext) => {
      this.pageInfos = context.pathStack
    })
  }
}
// PageTwo.ets
@Builder
export function PageTwoBuilder(name: string, param: Object) {
PageTwo()
}

@Component
export struct PageTwo {
pathStack: NavPathStack = new NavPathStack()
private menuItems: Array<NavigationMenuItem> = [
{
value: "1",
icon: 'resources/base/media/undo.svg',
},
{
value: "2",
icon: 'resources/base/media/redo.svg',
isEnabled: false,
},
{
value: "3",
icon: 'resources/base/media/ic_public_ok.svg',
isEnabled: true,
}
]

build() {
NavDestination() {
Column() {
Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.pathStack.pushPathByName('pageOne', null)
})
}.width('100%').height('100%')
}.title('pageTwo')
.menus(this.menuItems)
.onBackPressed(() => {
this.pathStack.pop()
return true
})
.onReady((context: NavDestinationContext) => {
this.pathStack = context.pathStack;
console.log("current page config info is " + JSON.stringify(context.getConfigInRouteMap()))
})
}
}
// 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
// route_map.json
{
  "routerMap": [
    {
      "name": "pageOne",
      "pageSourceFile": "src/main/ets/pages/PageOne.ets",
      "buildFunction": "PageOneBuilder",
      "data": {
        "description": "this is pageOne"
      }
    },
    {
      "name": "pageTwo",
      "pageSourceFile": "src/main/ets/pages/PageTwo.ets",
      "buildFunction": "PageTwoBuilder"
    }
  ]
}

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

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

// Index.ets
import { CustomTransition, AnimateCallback } from './CustomNavigationUtils'

@Entry
@Component
struct NavigationExample {
pageInfos: NavPathStack = new NavPathStack();

aboutToAppear() {
if (this.pageInfos === undefined) {
this.pageInfos = new NavPathStack();
}
this.pageInfos.pushPath({ name: 'pageOne', param: CustomTransition.getInstance().getAnimationId() });
}

build() {
Navigation(this.pageInfos) {
}
.title('NavIndex')
.hideNavBar(true)
.customNavContentTransition((from: NavContentInfo, to: NavContentInfo, operation: NavigationOperation) => {
if (from.mode == NavDestinationMode.DIALOG || to.mode == NavDestinationMode.DIALOG) {
return undefined;
}

// 首页不进行自定义动画
if (from.index === -1 || to.index === -1) {
return undefined;
}

CustomTransition.getInstance().operation = operation;
if (CustomTransition.getInstance().interactive) {
let customAnimation: NavigationAnimatedTransition = {
onTransitionEnd: (isSuccess: boolean) => {
console.log("===== current transition is " + isSuccess);
CustomTransition.getInstance().recoverState();
CustomTransition.getInstance().proxy = undefined;
},
transition: (transitionProxy: NavigationTransitionProxy) => {
CustomTransition.getInstance().proxy = transitionProxy;
let targetIndex: string | undefined = operation == NavigationOperation.PUSH ?
(to.navDestinationId) : (from.navDestinationId);
if (targetIndex) {
CustomTransition.getInstance().fireInteractiveAnimation(targetIndex, operation);
}
},
isInteractive: CustomTransition.getInstance().interactive
}
return customAnimation;
}
let customAnimation: NavigationAnimatedTransition = {
onTransitionEnd: (isSuccess: boolean) => {
console.log(`current transition result is ${isSuccess}`)
},
timeout: 7000,
// 转场开始时系统调用该方法,并传入转场上下文代理对象
transition: (transitionProxy: NavigationTransitionProxy) => {
if (!from.navDestinationId || !to.navDestinationId) {
return;
}
// 从封装类CustomTransition中根据子页面的序列获取对应的转场动画回调
let fromParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(from.navDestinationId);
let toParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(to.navDestinationId);
if (operation == NavigationOperation.PUSH) {
if (toParam.start) {
toParam.start(true, false);
}
animateTo({
duration: 500, onFinish: () => {
transitionProxy.finishTransition();
}
}, () => {
if (toParam.finish) {
toParam.finish(true, false);
}
})
} else {
if (fromParam.start) {
fromParam.start(true, true);
}
animateTo({
duration: 500, onFinish: () => {
transitionProxy.finishTransition();
}
}, () => {
if (fromParam.finish) {
fromParam.finish(true, true);
}
})
}
}
};
return customAnimation;
})
}
}
// PageOne.ets
import { CustomTransition } from './CustomNavigationUtils';

@Builder
export function PageOneBuilder(name: string, param: Object) {
  PageOne()
}

@Component
export struct PageOne {
  pageInfos: NavPathStack = new NavPathStack();
  @State translateX: string = '0';
  pageId: string = '';
  rectWidth: number = 0;
  interactive: boolean = false;

  registerCallback() {
    CustomTransition.getInstance().registerNavParam(this.pageId, (isPush: boolean, isExit: boolean) => {
      if (isPush) {
        this.translateX = '100%';
      } else {
        this.translateX = '0';
      }
    }, (isPush: boolean, isExit: boolean) => {
      if (isPush) {
        this.translateX = '0';
      } else {
        this.translateX = '100%';
      }
    }, (isPush: boolean, isExit: boolean) => {
      this.translateX = '0';
    }, (operation: NavigationOperation) => {
      if (operation == NavigationOperation.PUSH) {
        this.translateX = '100%';
        animateTo({
          duration: 1000,
          onFinish: () => {
            this.translateX = '0';
          }
        }, () => {
          this.translateX = '0';
        })
      } else {
        this.translateX = '0';
        animateTo({
          duration: 1000,
          onFinish: () => {
            this.translateX = '0';
          }
        }, () => {
          this.translateX = '100%';
        })
      }
    }, 200);
  }

  build() {
    NavDestination() {
      Column() {
        Button(`setInteractive`)
          .onClick(() => {
            CustomTransition.getInstance().interactive = !CustomTransition.getInstance().interactive;
            this.interactive = CustomTransition.getInstance().interactive;
          })

        Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            //将name指定的NavDestination页面信息入栈,传递的数据为param
            this.pageInfos.pushDestinationByName('pageTwo', CustomTransition.getInstance().getAnimationId());
          })
      }
      .size({ width: '100%', height: '100%' })
    }
    .title('pageOne')
    .onDisAppear(() => {
      CustomTransition.getInstance().unRegisterNavParam(this.pageId);
    })
    .onReady((context: NavDestinationContext) => {
      this.pageInfos = context.pathStack;
      if (context.navDestinationId) {
        this.pageId = context.navDestinationId;
        this.registerCallback();
      }
    })
    .translate({ x: this.translateX })
    .backgroundColor('#F1F3F5')
    .gesture(PanGesture()
      .onActionStart((event: GestureEvent) => {
        this.rectWidth = event.target.area.width as number;
        if (event.offsetX < 0) {
          this.pageInfos.pushPath({ name: 'pageTwo', param: CustomTransition.getInstance().getAnimationId() });
        } else {
          this.pageInfos.pop();
        }
      })
      .onActionUpdate((event: GestureEvent) => {
        let rate = event.fingerList[0].localX / this.rectWidth;
        CustomTransition.getInstance().updateProgress(rate);
      })
      .onActionEnd((event: GestureEvent) => {
        let rate: number = event.fingerList[0].localX / this.rectWidth;
        CustomTransition.getInstance().finishInteractiveAnimation(rate);
      }))
  }
}
// PageTwo.ets
import { CustomTransition } from './CustomNavigationUtils'

@Builder
export function PageTwoBuilder(name: string, param: Object) {
  PageTwo({ param: param as number })
}

@Component
export struct PageTwo {
  pageInfos: NavPathStack = new NavPathStack();
  @State translateX: string = '0';
  pageId: string = '';
  rectWidth: number = 0;
  param: number = 0;

  registerCallback() {
    CustomTransition.getInstance().registerNavParam(this.pageId, (isPush: boolean, isExit: boolean) => {
      if (isPush) {
        this.translateX = '100%'
      } else {
        this.translateX = '0';
      }
    }, (isPush: boolean, isExit: boolean) => {
      if (isPush) {
        this.translateX = '0';
      } else {
        this.translateX = '100%'
      }
    }, (isPush: boolean, isExit: boolean) => {
      this.translateX = '0';
    }, (operation: NavigationOperation) => {
      if (operation == NavigationOperation.PUSH) {
        this.translateX = '100%';
        animateTo({
          duration: 500, onFinish: () => {
            this.translateX = '0';
          }
        }, () => {
          this.translateX = '0'
        })
      } else {
        this.translateX = '0';
        animateTo({
          duration: 500, onFinish: () => {
            this.translateX = "0"
          }
        }, () => {
          this.translateX = '100%';
        })
      }
    }, 2000)
  }

  build() {
    NavDestination() {
      Column() {
        Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            //将name指定的NavDestination页面信息入栈,传递的数据为param
            this.pageInfos.pushPath({ name: 'pageOne', param: CustomTransition.getInstance().getAnimationId() })
          })
      }
      .size({ width: '100%', height: '100%' })
    }
    .title('pageTwo')
    .gesture(PanGesture()
      .onActionStart((event: GestureEvent) => {
        this.rectWidth = event.target.area.width as number;
        if (event.offsetX < 0) {
          this.pageInfos.pushPath({ name: 'pageOne', param: CustomTransition.getInstance().getAnimationId() });
        } else {
          this.pageInfos.pop();
        }
      })
      .onActionUpdate((event: GestureEvent) => {
        let rate = event.fingerList[0].localX / this.rectWidth;
        CustomTransition.getInstance().updateProgress(rate);
      })
      .onActionEnd((event: GestureEvent) => {
        let rate = event.fingerList[0].localX / this.rectWidth;
        CustomTransition.getInstance().finishInteractiveAnimation(rate);
      }))
    .onAppear(() => {
      this.registerCallback();
    })
    .onDisAppear(() => {
      CustomTransition.getInstance().unRegisterNavParam(this.pageId);
    })
    .onReady((context: NavDestinationContext) => {
      this.pageInfos = context.pathStack;
      if (context.navDestinationId) {
        this.pageId = context.navDestinationId;
        this.registerCallback();
      }
    })
    .translate({ x: this.translateX })
    .backgroundColor(Color.Yellow)
  }
}
// CustomNavigationUtils.ets
// 自定义接口,用来保存某个页面相关的转场动画回调和参数
export interface AnimateCallback {
  finish: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined;
  start: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined;
  onFinish: ((isPush: boolean, isExit: boolean) => void | undefined) | undefined;
  interactive: ((operation: NavigationOperation) => void | undefined) | undefined;
  timeout: (number | undefined) | undefined;
}

const customTransitionMap: Map<string, AnimateCallback> = new Map();

export class CustomTransition {
  static delegate = new CustomTransition();
  interactive: boolean = false;
  proxy: NavigationTransitionProxy | undefined = undefined;
  private animationId: number = 0;
  operation: NavigationOperation = NavigationOperation.PUSH

  static getInstance() {
    return CustomTransition.delegate;
  }

  /* 注册某个页面的动画回调
   * name: 注册页面的唯一id
   * startCallback:用来设置动画开始时页面的状态
   * endCallback:用来设置动画结束时页面的状态
   * onFinish:用来执行动画结束后页面的其他操作
   * interactiveCallback: 注册的可交互转场的动效
   * timeout:转场结束的超时时间
   */
  registerNavParam(name: string, startCallback: (operation: boolean, isExit: boolean) => void,
    endCallback: (operation: boolean, isExit: boolean) => void,
    onFinish: (operation: boolean, isExit: boolean) => void,
    interactiveCallback: (operation: NavigationOperation) => void,
    timeout: number): void {
    if (customTransitionMap.has(name)) {
      let param = customTransitionMap.get(name);
      if (param != undefined) {
        param.start = startCallback;
        param.finish = endCallback;
        param.timeout = timeout;
        param.onFinish = onFinish;
        param.interactive = interactiveCallback;
        return;
      }
    }
    let params: AnimateCallback = {
      timeout: timeout,
      start: startCallback,
      finish: endCallback,
      onFinish: onFinish,
      interactive: interactiveCallback
    };
    customTransitionMap.set(name, params);
  }

  getAnimationId() {
    return Date.now();
  }

  unRegisterNavParam(name: string): void {
    customTransitionMap.delete(name);
  }

  fireInteractiveAnimation(id: string, operation: NavigationOperation) {
    let animation = customTransitionMap.get(id)?.interactive;
    if (!animation) {
      return;
    }
    animation(operation);
  }

  updateProgress(progress: number) {
    if (!this.proxy?.updateTransition) {
      return;
    }
    progress = this.operation == NavigationOperation.PUSH ? 1 - progress : progress;
    this.proxy?.updateTransition(progress);
  }

  cancelTransition() {
    if (this.proxy?.cancelTransition) {
      this.proxy.cancelTransition();
    }
  }

  recoverState() {
    if (!this.proxy?.from.navDestinationId || !this.proxy?.to.navDestinationId) {
      return;
    }
    let fromParam = customTransitionMap.get(this.proxy.from.navDestinationId);
    if (fromParam?.onFinish) {
      fromParam.onFinish(false, false);
    }
    let toParam = customTransitionMap.get(this.proxy?.to.navDestinationId);
    if (toParam?.onFinish) {
      toParam.onFinish(true, true);
    }
  }

  finishTransition() {
    this.proxy?.finishTransition();
  }

  finishInteractiveAnimation(rate: number) {
    if (this.operation == NavigationOperation.PUSH) {
      if (rate > 0.5) {
        if (this.proxy?.cancelTransition) {
          this.proxy.cancelTransition();
        }
      } else {
        this.proxy?.finishTransition();
      }
    } else {
      if (rate > 0.5) {
        this.proxy?.finishTransition();
      } else {
        if (this.proxy?.cancelTransition) {
          this.proxy.cancelTransition();
        }
      }
    }
  }

  getAnimateParam(name: string): AnimateCallback {
    let result: AnimateCallback = {
      start: customTransitionMap.get(name)?.start,
      finish: customTransitionMap.get(name)?.finish,
      timeout: customTransitionMap.get(name)?.timeout,
      onFinish: customTransitionMap.get(name)?.onFinish,
      interactive: customTransitionMap.get(name)?.interactive,
    };
    return result;
  }
}
// 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
// route_map.json
{
  "routerMap": [
    {
      "name": "pageOne",
      "pageSourceFile": "src/main/ets/pages/PageOne.ets",
      "buildFunction": "PageOneBuilder",
      "data": {
        "description": "this is pageOne"
      }
    },
    {
      "name": "pageTwo",
      "pageSourceFile": "src/main/ets/pages/PageTwo.ets",
      "buildFunction": "PageTwoBuilder"
    }
  ]
}

示例4(Navigation带参返回)

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

// Index.ets

@Entry
@Component
struct NavigationExample {
  pageInfo: NavPathStack = new NavPathStack()

  build() {
    Navigation(this.pageInfo) {
      Column() {
        Button('StartTest', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pageInfo.pushPath({ name: 'pageOne' }); // 将name指定的NavDestination页面信息入栈。
          })
      }
    }.title('NavIndex')
  }
}
// PageOne.ets
import { BusinessError } from '@kit.BasicServicesKit';

class TmpClass {
  count: number = 10
}

class ParamWithOp {
  operation: number = 1
  count: number = 10
}

@Builder
export function PageOneBuilder(name: string, param: Object) {
  PageOne()
}

@Component
export struct PageOne {
  pageInfo: NavPathStack = new NavPathStack();
  @State message: string = 'Hello World'

  build() {
    NavDestination() {
      Column() {
        Text(this.message)
          .width('80%')
          .height(50)
          .margin(10)

        Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            this.pageInfo.pushPath({
              name: 'pageTwo', param: new ParamWithOp(), onPop: (popInfo: PopInfo) => {
                this.message =
                  '[pushPath]last page is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result);
              }
            }); // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
          })

        Button('pushPathByName', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            let tmp = new TmpClass()
            this.pageInfo.pushPathByName('pageTwo', tmp, (popInfo) => {
              this.message =
                '[pushPathByName]last page is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result);
            }); // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
          })

        Button('pushDestination', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            let tmp = new TmpClass()
            // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
            this.pageInfo.pushDestination({
              name: 'pageTwo', param: new ParamWithOp(), onPop: (popInfo: PopInfo) => {
                this.message =
                  '[pushDestination]last page is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result);
              }
            }).catch((error: BusinessError) => {
              console.error(`[pushDestination]failed, error code = ${error.code}, error.message = ${error.message}.`);
            }).then(() => {
              console.error('[pushDestination]success.');
            });
          })

        Button('pushDestinationByName', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            let tmp = new TmpClass()
            // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
            this.pageInfo.pushDestinationByName('pageTwo', tmp, (popInfo) => {
              this.message = '[pushDestinationByName]last page is: ' + popInfo.info.name + ', result: ' +
              JSON.stringify(popInfo.result);
            }).catch((error: BusinessError) => {
              console.error(`[pushDestinationByName]failed, error code = ${error.code}, error.message = ${error.message}.`);
            }).then(() => {
              console.error('[pushDestinationByName]success.');
            });
          })

        Button('pushPathWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            this.pageInfo.pushPath({ name: 'pageTwo', param: new ParamWithOp() }); // 将name指定的NavDestination页面信息入栈。
          })

        Button('pushPathByNameWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            let tmp = new TmpClass()
            this.pageInfo.pushPathByName('pageTwo', tmp); // 将name指定的NavDestination页面信息入栈,传递的数据为param。
          })

        Button('pushDestinationWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            let tmp = new TmpClass()
            // 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
            this.pageInfo.pushDestination({ name: 'pageTwo', param: new ParamWithOp() })
              .catch((error: BusinessError) => {
                console.error(`[pushDestinationWithoutOnPop]failed, error code = ${error.code}, error.message = ${error.message}.`);
              }).then(() => {
              console.error('[pushDestinationWithoutOnPop]success.');
            });
          })

        Button('pushDestinationByNameWithoutOnPop', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            let tmp = new TmpClass()
            // 将name指定的NavDestination页面信息入栈,传递的数据为param。
            this.pageInfo.pushDestinationByName('pageTwo', tmp)
              .catch((error: BusinessError) => {
                console.error(`[pushDestinationByNameWithoutOnPop]failed, error code = ${error.code}, error.message = ${error.message}.`);
              }).then(() => {
              console.error('[pushDestinationByNameWithoutOnPop]success.');
            });
          })

        Button('clear', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(10)
          .onClick(() => {
            this.pageInfo.clear(); // 清除栈中所有页面。
          })
      }.width('100%').height('100%')
    }.title('pageOne')
    .onBackPressed(() => {
      this.pageInfo.pop({ number: 1 }) // 弹出路由栈栈顶元素。
      return true
    }).onReady((context: NavDestinationContext) => {
      this.pageInfo = context.pathStack;
    })
  }
}
// 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
// route_map.json
{
"routerMap": [
{
"name": "pageOne",
"pageSourceFile": "src/main/ets/pages/PageOne.ets",
"buildFunction": "PageOneBuilder",
"data": {
"description": "this is pageOne"
}
},
{
"name": "pageTwo",
"pageSourceFile": "src/main/ets/pages/PageTwo.ets",
"buildFunction": "PageTwoBuilder"
}
]
}

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

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

let COLOR1: string = "#80004AAF";
let COLOR2: string = "#802787D9";
let BLUR_STYLE_1: BlurStyle = BlurStyle.BACKGROUND_THIN;
let BLUR_STYLE_2: BlurStyle = BlurStyle.BACKGROUND_THICK;

@Component
struct BackComponent {
  build() {
    Row() {
      Column() {
      }
      .height('100%')
      .backgroundColor("#3D9DB4")
      .layoutWeight(9)

      Column() {
      }
      .height('100%')
      .backgroundColor("#17A98D")
      .layoutWeight(9)

      Column() {
      }
      .height('100%')
      .backgroundColor("#FFC000")
      .layoutWeight(9)
    }
    .height('100%')
    .width('100%')
  }
}

@Component
struct ColorAndBlur {
  @State useColor1: boolean = true;
  @State useBlur1: boolean = true;

  build() {
    NavDestination() {
      Stack({ alignContent: Alignment.Center }) {
        BackComponent()
          .width('100%')
          .height('100%')
        Column() {
          Stack({ alignContent: Alignment.Center }) {
            Button("switch color")
              .onClick(() => {
                this.useColor1 = !this.useColor1;
              })
          }
          .width('100%')
          .layoutWeight(1)

          Stack({ alignContent: Alignment.Center }) {
            Button("switch blur")
              .onClick(() => {
                this.useBlur1 = !this.useBlur1;
              })
          }
          .width('100%')
          .layoutWeight(1)
        }
        .width('100%')
        .height('100%')
      }.width('100%')
      .height('100%')
    }
    .width('100%')
    .height('100%')
    // 开发者可以设置标题栏的背景颜色和背景模糊效果
    .title("switch titlebar color and blur", {
      backgroundColor: this.useColor1 ? COLOR1 : COLOR2,
      backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2,
      barStyle: BarStyle.STACK
    })
  }
}

@Entry
@Component
struct Index {
  private stack: NavPathStack = new NavPathStack();
  @State useColor1: boolean = true;
  @State useBlur1: boolean = true;

  @Builder
  PageBuilder(name: string) {
    ColorAndBlur()
  }

  build() {
    Navigation(this.stack) {
      Stack({ alignContent: Alignment.Center }) {
        BackComponent()
          .width('100%')
          .height('100%')
        Column() {
          Stack({ alignContent: Alignment.Center }) {
            Button("switch color")
              .onClick(() => {
                this.useColor1 = !this.useColor1;
              })
          }
          .width('100%')
          .layoutWeight(1)

          Stack({ alignContent: Alignment.Center }) {
            Button("switch blur")
              .onClick(() => {
                this.useBlur1 = !this.useBlur1;
              })
          }
          .width('100%')
          .layoutWeight(1)

          Stack({ alignContent: Alignment.Center }) {
            Button("push page")
              .onClick(() => {
                this.stack.pushPath({ name: "page" })
              })
          }
          .width('100%')
          .layoutWeight(1)
        }
        .width('100%')
        .height('80%')
      }.width('100%')
      .height('100%')
    }
    .width('100%')
    .height('100%')
    .navDestination(this.PageBuilder)
    // 开发者可以设置标题栏的背景颜色和背景模糊效果
    .title("NavTitle", {
      backgroundColor: this.useColor1 ? COLOR1 : COLOR2,
      backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2,
      barStyle: BarStyle.STACK
    })
    // 开发者可以设置工具栏的背景颜色和背景模糊效果
    .toolbarConfiguration([
      { value: "a" },
      { value: "b" },
      { value: "c" }
    ], {
      backgroundColor: this.useColor1 ? COLOR1 : COLOR2,
      backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2
    })
  }
}

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

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

@Entry
@Component
struct NavigationExample1 {
@State childNavStack: NavPathStack = new NavPathStack();

build() {
Navigation() {
Stack({ alignContent: Alignment.Center }) {
Navigation(this.childNavStack) {
Button('push Path to parent Navigation', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
// 可以获取父NavPathStack
let parentStack = this.childNavStack.getParent();
parentStack?.pushPath({ name: "pageOne" })
})
}
.clip(true)
.backgroundColor(Color.Orange)
.width('80%')
.height('80%')
.title('ChildNavigation')
}
.width('100%')
.height('100%')
}
.backgroundColor(Color.Green)
.width('100%')
.height('100%')
.title('ParentNavigation')
}
}
// PageOne.ets
  @Builder
  export function PageOneBuilder(name: string) {
    NavDestination() {
      Text("this is " + name)
    }
    .title(name)
  }
// 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
// route_map.json
{
"routerMap": [
{
"name": "pageOne",
"pageSourceFile": "src/main/ets/pages/PageOne.ets",
"buildFunction": "PageOneBuilder",
"data": {
"description": "this is pageOne"
}
}
]
}

示例7(通过onReady获取栈)

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

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

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

class PageParam {
  constructor(num_: number) {
    this.num = num_;
  }

  num: number = 0;
}

@Builder
export function PageOneBuilder(name: string, param: Object) {
  PageOne()
}

@Component
struct PageOne {
  private stack: NavPathStack | null = null;
  private name: string = "";
  private paramNum: number = 0;

  build() {
    NavDestination() {
      Column() {
        Text("NavPathInfo: name: " + this.name + ", paramNum: " + this.paramNum)
        Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            if (this.stack) {
              let p = new PageParam(this.paramNum + 1);
              this.stack.pushPath({ name: "pageOne", param: p });
            }
          })
        Button('pop', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.stack?.pop()
          })
      }
      .width('100%')
      .height('100%')
    }
    .title('pageOne')
    .onReady((ctx: NavDestinationContext) => {
      // 在NavDestination中能够拿到传来的NavPathInfo和当前所处的NavPathStack
      try {
        this.name = ctx?.pathInfo?.name;
        this.paramNum = (ctx?.pathInfo?.param as PageParam)?.num;
        this.stack = ctx.pathStack;
      } catch (e) {
        console.log(`testTag onReady catch exception: ${JSON.stringify(e)}`)
      }
    })
  }
}

@Entry
@Component
struct NavigationExample2 {
  private stack: NavPathStack = new NavPathStack();

  build() {
    Navigation(this.stack) {
      Stack({ alignContent: Alignment.Center }) {
        Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            let p = new PageParam(1);
            this.stack.pushPath({ name: "pageOne", param: p })
          })
      }
      .width('100%')
      .height('100%')
    }
    .width('100%')
    .height('100%')
    .title('Navigation')
  }
}
// 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
// route_map.json
{
  "routerMap": [
    {
      "name": "pageOne",
      "pageSourceFile": "src/main/ets/pages/Index.ets",
      "buildFunction": "PageOneBuilder",
      "data": {
        "description": "this is pageOne"
      }
    }
  ]
}

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

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

@Builder
export function PageOneBuilder(name: string, param: Object) {
PageOneComponent()
}

@Component
struct PageOneComponent {
private stack: NavPathStack | null = null;
@State eventStr: string = "";

build() {
NavDestination() {
Column() {
Text("event: " + this.eventStr)
Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
if (this.stack) {
this.stack.pushPath({ name: "pageOne" });
}
})
Button('pop', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.stack?.pop()
})
}
.width('100%')
.height('100%')
}
.title('pageOne')
.onAppear(() => {
this.eventStr += "<onAppear>";
})
.onDisAppear(() => {
this.eventStr += "<onDisAppear>";
})
.onShown(() => {
this.eventStr += "<onShown>";
})
.onHidden(() => {
this.eventStr += "<onHidden>";
})
.onWillAppear(() => {
this.eventStr += "<onWillAppear>";
})
.onWillDisappear(() => {
this.eventStr += "<onWillDisappear>";
})
.onWillShow(() => {
this.eventStr += "<onWillShow>";
})
.onWillHide(() => {
this.eventStr += "<onWillHide>";
})
// onReady会在onAppear之前调用
.onReady((ctx: NavDestinationContext) => {
try {
this.eventStr += "<onReady>";
this.stack = ctx.pathStack;
} catch (e) {
console.log(`testTag onReady catch exception: ${JSON.stringify(e)}`)
}
})
}
}

@Entry
@Component
struct NavigationExample3 {
private stack: NavPathStack = new NavPathStack();

build() {
Navigation(this.stack) {
Stack({ alignContent: Alignment.Center }) {
Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.stack.pushPath({ name: "pageOne" })
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
.title('Navigation')
}
}
// 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
// route_map.json
{
  "routerMap": [
    {
      "name": "pageOne",
      "pageSourceFile": "src/main/ets/pages/Index.ets",
      "buildFunction": "PageOneBuilder",
      "data": {
        "description": "this is pageOne"
      }
    }
  ]
}

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

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

@Entry
@Component
struct NavigationExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
private scrollerForScroll: Scroller = new Scroller();
@State barStyle: BarStyle = BarStyle.STANDARD;

build() {
Column() {
Navigation() {
Column() {
Scroll(this.scrollerForScroll) {
Column() {
Image($r('app.media.image_1'))// 设置与标题栏高度一致,以便观察STACK效果
.height(138)
.width('100%')
Button('BarStyle.STANDARD')
.height('50vp')
.onClick(() => {
this.barStyle = BarStyle.STANDARD;
})
Button('BarStyle.STACK')
.height('50vp')
.margin({ top: 12 })
.onClick(() => {
this.barStyle = BarStyle.STACK;
})

ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(Color.Orange)
.margin({ top: 12 })
}
}, (item: string) => item)
}
}
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
}
.title(
{
main: 'NavTitle',
sub: 'subtitle'
},
{
backgroundBlurStyle: BlurStyle.COMPONENT_THICK,
barStyle: this.barStyle,
}
)
.titleMode(NavigationTitleMode.Free)
.hideTitleBar(false)
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}

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

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

class DerivedNavPathStack extends NavPathStack {
// usr defined property 'id'
id: string = "__default__"

// new function in derived class
setId(id: string) {
this.id = id;
}

// new function in derived class
getInfo(): string {
return "this page used Derived NavPathStack, id: " + this.id
}

// overwrite function of NavPathStack
pushPath(info: NavPathInfo, animated?: boolean): void
pushPath(info: NavPathInfo, options?: NavigationOptions): void
pushPath(info: NavPathInfo, secArg?: boolean | NavigationOptions): void {
console.log('[derive-test] reached DerivedNavPathStack\'s pushPath');
if (typeof secArg === 'boolean') {
super.pushPath(info, secArg);
} else {
super.pushPath(info, secArg);
}
}

// overwrite and overload function of NavPathStack
pop(animated?: boolean | undefined): NavPathInfo | undefined
pop(result: Object, animated?: boolean | undefined): NavPathInfo | undefined
pop(result?: Object, animated?: boolean | undefined): NavPathInfo | undefined {
console.log('[derive-test] reached DerivedNavPathStack\'s pop');
return super.pop(result, animated);
}

// other function of base class...
}

class param {
info: string = "__default_param__";

constructor(info: string) {
this.info = info
}
}

@Entry
@Component
struct Index {
derivedStack: DerivedNavPathStack = new DerivedNavPathStack();

aboutToAppear(): void {
this.derivedStack.setId('origin stack');
}

@Builder
pageMap(name: string) {
PageOne()
}

build() {
Navigation(this.derivedStack) {
Button('to Page One').margin(20).onClick(() => {
this.derivedStack.pushPath({
name: 'pageOne',
param: new param('push pageOne in homePage when stack size: ' + this.derivedStack.size())
});
})
}.navDestination(this.pageMap)
.title('Home Page')
}
}

@Component
struct PageOne {
derivedStack: DerivedNavPathStack = new DerivedNavPathStack();
curStringifyParam: string = "NA";

build() {
NavDestination() {
Column() {
Text(this.derivedStack.getInfo())
.margin(10)
.fontSize(25)
.fontWeight(FontWeight.Bold)
.textAlign(TextAlign.Start)
Text('current page param info:')
.margin(10)
.fontSize(25)
.fontWeight(FontWeight.Bold)
.textAlign(TextAlign.Start)
Text(this.curStringifyParam)
.margin(20)
.fontSize(20)
.textAlign(TextAlign.Start)
}.backgroundColor(Color.Pink)

Button('to Page One').margin(20).onClick(() => {
this.derivedStack.pushPath({
name: 'pageOne',
param: new param('push pageOne in pageOne when stack size: ' + this.derivedStack.size())
});
})
}.title('Page One')
.onReady((context: NavDestinationContext) => {
console.log('[derive-test] reached PageOne\'s onReady');
// get derived stack from navdestinationContext
this.derivedStack = context.pathStack as DerivedNavPathStack;
console.log('[derive-test] -- got derivedStack: ' + this.derivedStack.id);
this.curStringifyParam = JSON.stringify(context.pathInfo.param);
console.log('[derive-test] -- got param: ' + this.curStringifyParam);
})
}
}

示例11(使用Symbol组件)

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

import { SymbolGlyphModifier } from '@kit.ArkUI';

@Entry
@Component
struct NavigationExample {
@Provide('navPathStack') navPathStack: NavPathStack = new NavPathStack();
@State menuItems: Array<NavigationMenuItem> = [
{
value: 'menuItem1',
icon: 'resources/base/media/ic_public_ok.svg' // 图标资源路径
},
{
value: 'menuItem2',
icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_folder_badge_plus')).fontColor([Color.Red, Color.Green])
.renderingStrategy(SymbolRenderingStrategy.MULTIPLE_COLOR),
},
{
value: 'menuItem3',
symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')),
},
]
@State toolItems: Array<ToolbarItem> = [
{
value: 'toolItem1',
icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')),
status: ToolbarItemStatus.ACTIVE,
activeSymbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_folder_badge_plus')).fontColor([Color.Red,
Color.Green]).renderingStrategy(SymbolRenderingStrategy.MULTIPLE_COLOR),
action: () => {
}
},
{
value: 'toolItem2',
symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_star')),
status: ToolbarItemStatus.ACTIVE,
activeIcon: 'resources/base/media/ic_public_more.svg', // 图标资源路径
action: () => {
}
},
{
value: 'toolItem3',
symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_star')),
status: ToolbarItemStatus.ACTIVE,
activeSymbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')),
action: () => {
}
}
]

@Builder
myRouter(name: string, param?: Object) {
if (name === 'NavigationMenu') {
NavigationMenu();
}
}

build() {
Navigation(this.navPathStack) {
Column() {
Button('跳转').onClick(() => {
this.navPathStack.pushPathByName('NavigationMenu', null);
})
}
}
.backButtonIcon(new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')))
.titleMode(NavigationTitleMode.Mini)
.menus(this.menuItems)
.toolbarConfiguration(this.toolItems)
.title('一级页面')
.navDestination(this.myRouter)
}
}

@Component
export struct NavigationMenu {
@Consume('navPathStack') navPathStack: NavPathStack;
@State menuItems: Array<NavigationMenuItem> = [
{
value: 'menuItem1',
icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
action: () => {
}
},
{
value: 'menuItem2',
symbolIcon: new SymbolGlyphModifier($r('sys.symbol.ohos_folder_badge_plus')).fontColor([Color.Red, Color.Green])
.renderingStrategy(SymbolRenderingStrategy.MULTIPLE_COLOR),
action: () => {
}
},
{
value: 'menuItem3',
symbolIcon: new SymbolGlyphModifier($r('sys.symbol.repeat_1')),
action: () => {
}
},
]

build() {
NavDestination() {
Row() {
Column() {
}
.width('100%')
}
.height('100%')
}
.hideTitleBar(false)
.title('NavDestination title')
.backgroundColor($r('sys.color.ohos_id_color_titlebar_sub_bg'))
.backButtonIcon(new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Blue]))
.menus(this.menuItems)
}
}

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

该示例主要演示Navigation和NavDestination如何自定义设置标题栏边距。

import { LengthMetrics } from '@kit.ArkUI';

@Entry
@Component
struct NavigationExample {
  @Provide('navPathStack') navPathStack: NavPathStack = new NavPathStack();
  // 初始化标题栏起始端内间距
  @State paddingStart: LengthMetrics = LengthMetrics.vp(0);
  // 初始化标题栏结束端内间距
  @State paddingEnd: LengthMetrics = LengthMetrics.vp(0);
  @State menuItems: Array<NavigationMenuItem> = [
    {
      value: 'menuItem1',
      icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
      action: () => {
      }
    }
  ]

  @Builder
  myRouter(name: string, param?: Object) {
    if (name === 'NavDestinationExample') {
      NavDestinationExample();
    }
  }

  build() {
    Navigation(this.navPathStack) {
      Column() {
        // 标题栏内间距切换
        Button('切换标题栏内间距为16vp')
          .onClick(() => {
            this.paddingStart = LengthMetrics.vp(16);
            this.paddingEnd = LengthMetrics.vp(16);
          })
          .margin({ top: 5 })

        Button('切换标题栏内间距为24vp')
          .onClick(() => {
            this.paddingStart = LengthMetrics.vp(24);
            this.paddingEnd = LengthMetrics.vp(24);
          })
          .margin({ top: 5 })

        Button('跳转')
          .onClick(() => {
            this.navPathStack.pushPathByName('NavDestinationExample', null);
          })
          .margin({ top: 5 })
      }
    }
    .titleMode(NavigationTitleMode.Mini)
    .title('一级页面', {
      paddingStart: this.paddingStart,
      paddingEnd: this.paddingEnd,
    })
    .menus(this.menuItems)
    .navDestination(this.myRouter)
  }
}

@Component
export struct NavDestinationExample {
  @Consume('navPathStack') navPathStack: NavPathStack;
  @State menuItems: Array<NavigationMenuItem> = [
    {
      value: 'menuItem1',
      icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
      action: () => {
      }
    }
  ]
  @State paddingStart: LengthMetrics = LengthMetrics.vp(0);
  @State paddingEnd: LengthMetrics = LengthMetrics.vp(0);

  build() {
    NavDestination() {
      Row() {
        Column() {
          // 标题栏内间距切换
          Button('切换标题栏内间距为32vp')
            .onClick(() => {
              this.paddingStart = LengthMetrics.vp(32);
              this.paddingEnd = LengthMetrics.vp(32);
            })
            .margin({ top: 5 })

          Button('切换标题栏内间距为20vp')
            .onClick(() => {
              this.paddingStart = LengthMetrics.vp(20);
              this.paddingEnd = LengthMetrics.vp(20);
            })
            .margin({ top: 5 })
        }
        .width('100%')
      }
      .height('100%')
    }
    .hideTitleBar(false)
    .title('NavDestination title', {
      paddingStart: this.paddingStart,
      paddingEnd: this.paddingEnd,
    })
    .menus(this.menuItems)
  }
}

鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:Navigation) ArkTS声明式开发(基础手势:Navigation) 阅读详情

相关推荐

鸿蒙5.0版开发:ArkTS组件-基础组件(Navigation)

Navigation组件是路由导航的根视图容器,一般作为Page页面的根容器使用...

m0_69424697的博客 2171

【HarmonyOS NEXT 】应用开发:ArkTS导航组件一(Navigation)

Navigation组件一般作为页面的根容器,包括单页面、分栏和自适应三种显示模式。同时,Navigation提供了属性来设置页面的标题栏、工具栏、导航栏等。

weixin_47351913的博客 2461

HarmonyOS NEXT开发实战:Navigation页面跳转对象传递案例

本示例主要介绍在使用Navigation实现页面跳转时,如何在跳转页面得到转入页面传的类对象的方法。

m0_72493819的博客 1723

ArKTS的基本组件

设置文本的字体粗细,number类型取值[100, 900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如“400”,以及“bold”、“bolder”、“lighter”、“regular”、“medium”,分别对应FontWeight中相应的枚举值。当文本内容较多超出了Text组件范围的时候,您可以使用textOverflow设置文本截取方式,需配合maxLines使用,单独设置不生效,maxLines用于设置文本显示最大行数。

morr_的博客 6965

鸿蒙开发5.0【UI开发技巧】

让TextInput再次获取焦点,并弹出键盘,可调用下面方法,参数为TextInput的id/key

2401_82772199的博客 1278

鸿蒙5.0进阶开发:UI开发-使用XComponent实现画中画功能开发

本文以视频播放为例,介绍通过XComponent实现画中画功能的基本开发步骤。

AyomQAQ的博客 1079

鸿蒙5.0开发进阶:UI框架-ArkTS组件(NavDestination)

作为子页面的根容器,用于显示Navigation的内容区。

Androidbye的博客 1125

鸿蒙(HarmonyOS)Navigation如何实现多场景UI适配?

在窄屏设备上,联系人和聊天区在多窗口中体现。在宽屏设备上,联系人和聊天区在同一窗口体现。要做好适配,往往需要开发者开发多套代码,以便运行在不同设备上。但是这样耗时耗力,于是ArkUI针对这种场景提供了分栏组件,可以通过一套代码完成不同设别的适配,本例简单介绍下如何使用分栏组件实现上述场景。

maniuT的博客 1930

HarmonyOS6 ArkTS Navigation

Navigation 是HarmonyOS6中实现页面导航的基础核心组件,其与NavDestination的组合是官方推荐的标准导航布局方式,具备布局规范、多端适配、配置灵活等特点。本示例通过状态管理+条件渲染的方式,实现了主/子页面的基础切换,代码简洁、可直接运行,符合HarmonyOS6 ArkTS的开发规范。

qq_37048082的博客 5838

【鸿蒙ArkUI实战开发】基于tabs实现页面布局

在页面布局过程中,Tabs可以将产品包含的所有内容进行清晰分类,一目了然地呈现应用的内容范围,方便概览与跳转场景一:tab嵌套list的吸顶效果场景二:tabbar样式自定义:1、tabs切换、监听2、样式自定义3、tabbar尾端文字渐变场景三:tabContent切换动画方案一:实现思路:1、最外层为tabs组件,首页tabContent主要用的stack组件嵌套了scroll组件+导航输入框组件,其中scroll组件嵌套了tabs组件,tabs里面嵌套list组件。2、外层的滚动组件scroll主要通

MNXN666的博客 1272

STM32——IIC(I2C)中断与DMA通信实战解析

本文深入解析STM32的IIC(I2C)通信中断与DMA实战应用。通过对比轮询方式的低效,详细介绍中断模式和DMA模式的实现原理、状态机编程技巧及性能优化策略,并结合SHT30传感器案例展示如何高效读取数据,显著提升系统响应速度和CPU利用率。

week9的博客 808

鸿蒙应用开发完全指南,涵盖ArkTS语法、UI组件等

《鸿蒙应用开发完全指南》摘要:本文系统介绍了华为HarmonyOS应用开发的学习路径。首先讲解HarmonyOS的分布式架构特点和开发环境搭建,通过"Hello World"示例展示基础开发流程。重点解析ArkTS语言核心语法,包括声明式UI、状态管理等特性,并详细演示常用UI组件(Text/Button/List等)和容器布局(Column/Row/Flex)的使用方法。最后涵盖数据库操作等进阶内容,帮助开发者从零开始掌握鸿蒙应用开发全流程,构建跨设备分布式应用。

woshi_xiaoa的博客 239

Multisim仿真电路:(十二)MOS管缓启动电路设计与优化

本文详细介绍了基于Multisim的MOS管缓启动电路设计与优化方法。通过分析米勒平台效应,探讨RC参数选择、多级设计和有源电路等技巧,有效抑制冲击电流并优化开关损耗。文章结合仿真实例,提供实用的设计策略和实际应用注意事项,帮助工程师提升电源管理系统的可靠性。

pytorch8learner的博客 237

鸿蒙HarmonyOS 5.0开发实战:沉浸式适配实现案例

本案例分别针对Navigation、滚动、Web页、底部弹框等场景实现了沉浸式适配,且介绍了实现沉浸式适配的两种方案。

m0_73088370的博客 960

基于知识图谱的电影推荐系统——Neo4j&Python

也可直接从这里下载:链接: https://pan.baidu.com/s/1l6wjwcUzy5G_dIlVDbCkpw 提取码: pkq6。修改main.py中的driver,输入自己数据库的用户名与密码。系统会询问是否需要重新加载并创建知识图谱,在第一次时输入1。

weixin_46351593的博客 6357

数据可视化—power bi 基础操作汇总

数据来源: https://pan.baidu.com/s/1U_Y7rKfhnSKbLmh4FcUD_Q 提取码: yq5v 目录 基本功能与视图 编辑与查询—修改column案例 建立关联性 新增column与DAX完成总价运算 习题练习1:建立可视化图表 产品销售统计图 column拖曳可视化 1.基本功能与视图 ①基础操作界面 ②获取数据—以打开excel为例 ③数据文件基本视图 可视化形式:柱状图、数据、关联性 2.编辑与查询—修改column ①编辑与查询—数据处理界面 .

weixin_52730784的博客 2683

鸿蒙5.0进阶开发:UI开发-导航转场

导航转场是页面的路由转场方式,也就是一个界面消失,另外一个界面出现的动画效果。

AyomQAQ的博客 860

Python抓取摄像头图像,进行AI识别(一)

本文介绍了如何用Python获取海康威视摄像头的图像并进行AI识别。主要内容包括:1)准备工作,包括摄像头IP设置和密码重置方法;2)使用Python的Requests库通过ISAPI接口获取实时图像;3)示例代码展示如何保存摄像头图像。整个过程为后续AI图像识别提供了基础,通过简单的Python代码即可实现专业监控设备的图像采集功能。

Hahafantuan的博客 1517

HarmonyOS 鸿蒙App开发不难:一个前端工程师的 ArkTS 上手实践

一个前端工程师的 HarmonyOS 上手实录,附一个已上架的真实应用。

liliang8164的博客 602

避坑指南:在Ubuntu 20.04上从零部署IS-Fusion环境(含CUDA 11.1和PyTorch 1.10.1配置)

本文提供了在Ubuntu 20.04系统上从零部署IS-Fusion 3D目标检测环境的详细避坑指南。内容涵盖CUDA 11.1、PyTorch 1.10.1、spconv等核心组件的精确版本安装与兼容性配置,并指导如何准备nuScenes数据集及启动模型训练,旨在帮助研究者和开发者高效搭建稳定的多模态融合算法开发环境。

gitlab7runner的博客 553

开关电源EMC整改实录:用WSX系列共模电感搞定30MHz辐射超标

本文详细介绍了开关电源EMC整改实战,通过WSX系列共模电感成功解决30MHz频段辐射超标问题。文章分析了共模干扰的产生机制,对比了不同磁芯材料的性能差异,并提供了电路布局优化与安装技巧,最终通过实测数据验证了整改方案的有效性。

weixin_29305313的博客 417

HarmonyOS6 ArkTS NavDestination

通过存储滚动组件的垂直偏移量,作为标题栏模式切换的判断依据;NavDestination作为HarmonyOS 6中构建页面体系的核心组件,其核心价值在于实现了页面的模块化封装与与Navigation、滚动组件的深度联动。通过简单的属性配置,即可实现标题自定义、返回按钮控制、安全区自适应等基础能力,结合Scroll/List的滚动监听,还能实现沉浸式的标题栏联动效果,是HarmonyOS 6 ArkTS开发中不可或缺的组件。

qq_37048082的博客 5585

【电力系统】高压直流输电VSC-HVDC,四个变流站联合输电 / 交直流混合并网系统

本文研究了一种基于电压源型换流器(VSC)的高压直流输电(HVDC)系统,该系统通过四个变流站实现联合输电并接入交直流混合电网。文章介绍了系统的结构、工作原理以及控制策略,分析了交直流混合并网的特性,并通过仿真验证了系统的性能。结果表明,该系统具有良好的稳定性和灵活性,能够有效实现多点供电和功率协调。

2401_84610415的博客 2243

鸿蒙开发(API12)通过组件导航Navigation配合NavPathStack实现页面路由

在跳转之前需要在app/entry/src/main/resources/base/profile中新建文件route_map.json文件名可以随意,在文件中对子页面进行注册,并在PageTwo文件中写一个builder方法,最后在app/entry/src/main/module.json5,module.json5中绑定route_map.json,最后可以完成tia。属性进行隐藏,导航页不存在页面栈中,导航页和子页,以及子页之间可以通过路由操作进行切换。在API Version 9上,需要配合。

2301_81830829的博客 1142

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

HarmonyOS应用开发实战:小事记 - @ohos.router 与 Navigation 组件对比:路由栈管理与生命周期差异

摘要:本文对比了HarmonyOS的两种页面路由方案——轻量级API @ohos.router 和声明式容器 Navigation 组件。 功能差异:Navigation 提供更丰富的路由栈管理(如指定出栈、清空栈),支持页面间数据返回,而 @ohos.router 仅支持基础跳转和替换。 生命周期:两者均触发标准生命周期,但 Navigation 能更精细控制中间页面的销毁。 实践问题:分析小事记项目中 BottomTabBar 使用 router.replaceUrl 导致的路由栈丢失和状态无法保留问题

红烧大青虫的博客 1047

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

鸿蒙5.0开发实战案例:应用沉浸式效果

典型应用全屏窗口UI元素包括 状态栏 、应用界面和底部 导航条。开发应用沉浸式效果主要指通过调整状态栏、应用界面和导航条的显示效果来减少状态栏导航条等系统界面的突兀感,从而使用户获得最佳的UI体验。图1界面元素示意图UI元素避让处理:导航条底部区域可以响应点击事件,除此之外的可交互UI元素和应用关键信息不建议放到导航条区域。沉浸式效果处理:将状态栏和导航条颜色与界面元素颜色相匹配,不出现明显的突兀感。

liudiaosi6的博客 818

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

上一篇: 鸿蒙5.0开发进阶:UI框架-ArkTS组件(SwipeRefresher)
下一篇: 鸿蒙5.0开发进阶:UI框架-ArkTS组件(NavRouter)
懂你的大海
博客等级 码龄6年 9049粉丝 1381原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值