鸿蒙5.0版开辟:ArkTS组件-Navigation

打印 上一主题 下一主题

主题 1068|帖子 1068|积分 3208

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



  • 鸿蒙开辟核心知识点,看这篇文章就够了
  • 最新版!鸿蒙HarmonyOS Next应用开辟实战学习路线
  • 鸿蒙HarmonyOS NEXT开辟技能最全学习路线指南
  • 鸿蒙应用开辟实战项目,看这一篇文章就够了(部门项目附源码)

Navigation

Navigation组件是路由导航的根视图容器,一般作为Page页面的根容器使用,其内部默认包含了标题栏、内容区和工具栏,其中内容区默认首页显示导航内容(Navigation的子组件)或非首页显示,首页和非首页通过路由进行切换。
   说明:
  该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
  该组件从API Version 11开始默认支持安全区避让特性(默认值为:expandSafeArea([SafeAreaType.SYSTEM, SafeAreaType.KEYBOARD, SafeAreaType.CUTOUT], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])),开辟者可以重写该属性覆盖默认行为,API Version 11之前的版本需共同expandSafeArea属性实现安全区避让。
  子组件

可以包含子组件。
从API Version 9开始,保举与NavRouter组件搭配使用。
从API Version 10开始,保举使用NavPathStack共同navDestination属性进行页面路由。
接口

Navigation

Navigation()
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
Navigation10+

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

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
参数:
参数名类型必填说明value Array<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: 显示返回键。 navBarWidth9+

navBarWidth(value: Length)
设置导航栏宽度。仅在Navigation组件分栏时见效。
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名类型必填说明valueLength是导航栏宽度。
默认值:240
单元:vp
undefined:行为不做处理,导航栏宽度与默认值保持一致。 navBarPosition9+

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 navDestination10+

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页面详细参数。 navBarWidthRange10+

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)   说明:
  

  • 仅设置navBarWidth,不支持Navigation分割线拖拽。
  • navBarWidthRange指定分割线可以拖拽范围。假如不设置值,则按照默认值处理。拖拽范围必要满足navBarWidthRange设置的范围和minContentWidth限制。
  • 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>是系统状态栏样式。   使用说明:
  

  • 不建议混淆使用systemBarStyle属性和window设置状态栏样式的相关接口。
  • 初次设置Navigation/NavDestination的systemBarStyle属性时,会备份当前状态栏样式用于后续的规复场景。
  • Navigation总是以首页(页面栈内没有NavDestination时)或者栈顶NavDestination设置的状态栏样式为准。
  • Navigation首页或者任何栈顶NavDestination页面,假如设置了有效的systemBarStyle,则会使用设置的样式,反之假如之前已经备份了样式,则使用备份的样式,否则不做任那边理。
  • Split模式下的Navigation,假如内容区没有NavDestination,则遵从Navigation首页的设置,反之则遵从栈顶NavDestination的设置。
  • 仅支持在主窗口的主页面中使用systemBarStyle设置状态栏样式。
  • 仅当Navigation占满整个页面时,设置的样式才访问效,当Navigation没有占满整个页面时,假如有备份的样式,则规复备份的样式。
  • 当页面设置差别样式时,在页面转场开始时见效。
  • 非全屏窗口下,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(delegatefrom: NavContentInfo, to: NavContentInfo, operation: NavigationOperation) => NavigationAnimatedTransition | undefined)
自界说转场动画回调。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名类型必填说明fromNavContentInfo是退场Destination的页面。toNavContentInfo是出场Destination的页面。operationNavigationOperation是转场类型。 返回值:
类型说明NavigationAnimatedTransition | undefined自界说转场动画协议。
undefined: 返回未界说,实行默认转场动效。 NavPathStack10+

Navigation路由栈,允许被继承12+。开辟者可以在派生类中新增属性方法,也可以重写基类NavPathStack的方法。派生类对象可以替换基类NavPathStack对象使用。
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<opInfo>, animated?: boolean): void
将name指定的NavDestination页面信息入栈,传递的数据为param,添加onPop回调接收入栈页面出栈时的返回结果,并进行处理。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名类型必填说明namestring是NavDestination页面名称。paramObject是NavDestination页面详细参数。onPopCallback<opInfo>是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<opInfo>, animated?: boolean): Promise<void>
将name指定的NavDestination页面信息入栈,传递的数据为param,并且添加用于页面出栈时处理返回结果的OnPop回调,使用Promise异步回调返回接口调用结果。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
参数:
参数名类型必填说明namestring是NavDestination页面名称。paramObject是NavDestination页面详细参数。onPopCallback<opInfo>是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跳转拦截对象。 NavPathInfo10+

路由页面信息。
constructor

constructor(name: string, param: unknown, onPop?: Callback<opInfo>, isEntry?: boolean)
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
参数名类型必填说明namestring是NavDestination页面名称。paramunknown是NavDestination页面详细参数。onPop11+Callback<opInfo>否NavDestination页面触发pop时返回的回调。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<opInfo>否NavDestination页面触发pop时返回的回调。isEntry12+boolean否标记NavDestination是否为入口页面。
默认值:false
标记清理时机:1、在当前navDestination页面触发一次全局back事件。2、应用退至背景。
说明
入口NavDestination不相应应用内的全局back事件,直打仗发应用间的全局back事件。 PopInfo11+

下一个页面返回的回调信息载体。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
名称类型必填说明infoNavPathInfo是页面触发返回时的当前页面信息,系统主动获取填入,无需开辟者传入。resultObject是页面触发返回时的结果,开辟者自界说对象。 NavContentInfo11+

跳转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的唯一标识符。 NavigationAnimatedTransition11+

自界说转场动画协议,开辟者需实现该协议来界说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。 NavigationTransitionProxy 11+

自界说转场动画代理对象。
系统能力: 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。 NavigationInterception12+

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是导航栏的显示模式。 NavBar12+

type NavBar = ‘navBar’
Navigation首页名字。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
类型说明“navBar”Navigation首页。 NavigationMenuItem

系统能力: 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.NORMALactiveIconResourceStr否工具栏单个选项处于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对应的图片资源。 NavigationTitleMode摆列说明

原子化服务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。 NavigationCommonTitle9+

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
名称类型必填说明mainstring是设置主标题。substring是设置副标题。 NavigationCustomTitle9+

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
名称类型必填说明builderCustomBuilder是设置标题栏内容。heightTitleHeight | Length是设置标题栏高度。 NavBarPosition9+摆列说明

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
名称描述Start双栏显示时,主列在主轴方向首部。End双栏显示时,主列在主轴方向尾部。 NavigationMode9+摆列说明

原子化服务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,且分割线不可拖动。AutoAPI version 9之前:窗口宽度>=520vp时,采用Split模式显示;窗口宽度<520vp时,采用Stack模式显示。
API version 10及以上:窗口宽度>=600vp时,采用Split模式显示;窗口宽度<600vp时,采用Stack模式显示,600vp即是minNavBarWidth(240vp) + minContentWidth (360vp)。 NavigationOperation11+摆列说明

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
名称描述PUSH本次转场为页面出场。POP本次转场为页面退场。REPLACE本次转场为页面替换。 BarStyle12+摆列说明

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
名称描述STANDARD标题栏与内容区采用上下结构。STACK标题栏与内容区采用层叠结构,标题栏结构在内容区上层。 NavigationTitleOptions11+

系统能力: 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开始,该接口支持在原子化服务中使用。 NavigationToolbarOptions11+

原子化服务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模式相比,该方法不会复用栈中同名实例。 NavigationOptions12+

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.ArkUI.ArkUI.Full
名称类型必填说明launchModeLaunchMode否页面栈的操纵模式。
默认值:LaunchMode.STANDARDanimatedboolean否是否支持转场动画。
默认值:true。 示例

示例效果请以真机为准。
示例1

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

示例2

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

示例3

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

示例4

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

示例5

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

示例6

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

示例7

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

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

示例8

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

示例9

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

示例10

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

示例11

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

示例12

该示例主要演示Navigation和NavDestination如何自界说设置标题栏边距。
  1. import { LengthMetrics } from '@kit.ArkUI';
  2. @Entry
  3. @Component
  4. struct NavigationExample {
  5.   @Provide('navPathStack') navPathStack: NavPathStack = new NavPathStack();
  6.   // 初始化标题栏起始端内间距
  7.   @State paddingStart: LengthMetrics = LengthMetrics.vp(0);
  8.   // 初始化标题栏结束端内间距
  9.   @State paddingEnd: LengthMetrics = LengthMetrics.vp(0);
  10.   @State menuItems: Array<NavigationMenuItem> = [
  11.     {
  12.       value: 'menuItem1',
  13.       icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
  14.       action: () => {
  15.       }
  16.     }
  17.   ]
  18.   @Builder
  19.   myRouter(name: string, param?: Object) {
  20.     if (name === 'NavDestinationExample') {
  21.       NavDestinationExample();
  22.     }
  23.   }
  24.   build() {
  25.     Navigation(this.navPathStack) {
  26.       Column() {
  27.         // 标题栏内间距切换
  28.         Button('切换标题栏内间距为16vp')
  29.           .onClick(() => {
  30.             this.paddingStart = LengthMetrics.vp(16);
  31.             this.paddingEnd = LengthMetrics.vp(16);
  32.           })
  33.           .margin({ top: 5 })
  34.         Button('切换标题栏内间距为24vp')
  35.           .onClick(() => {
  36.             this.paddingStart = LengthMetrics.vp(24);
  37.             this.paddingEnd = LengthMetrics.vp(24);
  38.           })
  39.           .margin({ top: 5 })
  40.         Button('跳转')
  41.           .onClick(() => {
  42.             this.navPathStack.pushPathByName('NavDestinationExample', null);
  43.           })
  44.           .margin({ top: 5 })
  45.       }
  46.     }
  47.     .titleMode(NavigationTitleMode.Mini)
  48.     .title('一级页面', {
  49.       paddingStart: this.paddingStart,
  50.       paddingEnd: this.paddingEnd,
  51.     })
  52.     .menus(this.menuItems)
  53.     .navDestination(this.myRouter)
  54.   }
  55. }
  56. @Component
  57. export struct NavDestinationExample {
  58.   @Consume('navPathStack') navPathStack: NavPathStack;
  59.   @State menuItems: Array<NavigationMenuItem> = [
  60.     {
  61.       value: 'menuItem1',
  62.       icon: 'resources/base/media/ic_public_ok.svg', // 图标资源路径
  63.       action: () => {
  64.       }
  65.     }
  66.   ]
  67.   @State paddingStart: LengthMetrics = LengthMetrics.vp(0);
  68.   @State paddingEnd: LengthMetrics = LengthMetrics.vp(0);
  69.   build() {
  70.     NavDestination() {
  71.       Row() {
  72.         Column() {
  73.           // 标题栏内间距切换
  74.           Button('切换标题栏内间距为32vp')
  75.             .onClick(() => {
  76.               this.paddingStart = LengthMetrics.vp(32);
  77.               this.paddingEnd = LengthMetrics.vp(32);
  78.             })
  79.             .margin({ top: 5 })
  80.           Button('切换标题栏内间距为20vp')
  81.             .onClick(() => {
  82.               this.paddingStart = LengthMetrics.vp(20);
  83.               this.paddingEnd = LengthMetrics.vp(20);
  84.             })
  85.             .margin({ top: 5 })
  86.         }
  87.         .width('100%')
  88.       }
  89.       .height('100%')
  90.     }
  91.     .hideTitleBar(false)
  92.     .title('NavDestination title', {
  93.       paddingStart: this.paddingStart,
  94.       paddingEnd: this.paddingEnd,
  95.     })
  96.     .menus(this.menuItems)
  97.   }
  98. }
复制代码




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

东湖之滨

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表