赞
踩
harmonyOS系统自带的tabs容器只能在tabbar上显示文本,不能添加图形。如果要实现下面这种常见的效果,需要通过自定义导航栏实现,这个方法在3.1/4.0版本配套文档(对应API9)中有介绍,在3.0的配套文档中(对应API8)是没有的,但是实际上也是可以生效的。
以下是3.1/4.0版本配套文档的介绍
Tabs-组件导航-设置页面路由和组件导航-基于ArkTS的声明式开发范式-UI开发-开发-HarmonyOS应用开发
官方给出的样例一共有四个输入
title:tabbar显示的文本
targetId:tabbar的唯一编号
selectedImg:激活时的图标
normalImg:去激活时的图标
这个自定义的tabbar只有一个图片和一个文本上下布局,采用线性布局的Column。增加onClick方法控制激活时的行为
- @Builder TabBuilder(title: string, targetId: number, selectedImg: Resource, normalImg: Resource) {
- Column() {
- Image(this.currentIndex === targetId ? selectedImg : normalImg)
- .size({ width: 30, height: 30 })
- .margin({ bottom: 4 })
- Text(title).fontColor(this.currentIndex === targetId ? '#1698ce' : '#6b6b6b')
- }.width('100%').height(40).justifyContent(FlexAlign.Center)
- .onClick(() => {
- this.currentIndex = targetId
- this.controller.changeIndex(this.currentIndex)
- })
- }
如下实现完整的自定义的tabs页面
- @Entry
- @Component
- struct Index {
- @State currentIndex: number = 0
- private controller: TabsController = new TabsController()
-
- @Builder TabBuilder(title: string, targetId: number, selectedImg: Resource, normalImg: Resource) {
- Column() {
- Image(this.currentIndex === targetId ? selectedImg : normalImg)
- .size({ width: 30, height: 30 })
- .margin({ bottom: 4 })
- Text(title).fontColor(this.currentIndex === targetId ? '#1698ce' : '#6b6b6b')
- }.width('100%').height(40).justifyContent(FlexAlign.Center)
- .onClick(() => {
- this.currentIndex = targetId
- this.controller.changeIndex(this.currentIndex)
- })
-
- }
-
- build() {
- Column() {
- Row() {
- Text('聊天精灵').textAlign(TextAlign.Center).fontSize(18)
- }.margin({ top: 10, bottom: 10 }).height('5%')
-
- Tabs({ barPosition: BarPosition.End, controller: this.controller, index: this.currentIndex }) {
- TabContent() {
- }.tabBar(this.TabBuilder('我的', 0, $r('app.media.chat_selected'), $r('app.media.chat_normal')))
-
- TabContent() {
-
- }.tabBar(this.TabBuilder('他的', 1, $r('app.media.others_s'), $r('app.media.others_n')))
-
- TabContent() {
-
- }.tabBar(this.TabBuilder('设置', 2, $r('app.media.setting_s'), $r('app.media.setting_n')))
-
- }
- .vertical(false)
- .height('90%')
- .barMode(BarMode.Fixed)
- .barWidth(400)
- .barHeight(60)
- .animationDuration(400)
- .onChange((index: number) => {
- this.currentIndex = index
- this.controller.changeIndex(this.currentIndex)
- })
-
- }.backgroundColor("#eeeeee")
-
- }
- }

最终效果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。