当前位置:   article > 正文

HarmonyOS开发-实现自定义的tabs容器_harmony tabs.margin

harmony tabs.margin

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方法控制激活时的行为

  1. @Builder TabBuilder(title: string, targetId: number, selectedImg: Resource, normalImg: Resource) {
  2. Column() {
  3. Image(this.currentIndex === targetId ? selectedImg : normalImg)
  4. .size({ width: 30, height: 30 })
  5. .margin({ bottom: 4 })
  6. Text(title).fontColor(this.currentIndex === targetId ? '#1698ce' : '#6b6b6b')
  7. }.width('100%').height(40).justifyContent(FlexAlign.Center)
  8. .onClick(() => {
  9. this.currentIndex = targetId
  10. this.controller.changeIndex(this.currentIndex)
  11. })
  12. }

​如下实现完整的自定义的tabs页面​

  1. @Entry
  2. @Component
  3. struct Index {
  4. @State currentIndex: number = 0
  5. private controller: TabsController = new TabsController()
  6. @Builder TabBuilder(title: string, targetId: number, selectedImg: Resource, normalImg: Resource) {
  7. Column() {
  8. Image(this.currentIndex === targetId ? selectedImg : normalImg)
  9. .size({ width: 30, height: 30 })
  10. .margin({ bottom: 4 })
  11. Text(title).fontColor(this.currentIndex === targetId ? '#1698ce' : '#6b6b6b')
  12. }.width('100%').height(40).justifyContent(FlexAlign.Center)
  13. .onClick(() => {
  14. this.currentIndex = targetId
  15. this.controller.changeIndex(this.currentIndex)
  16. })
  17. }
  18. build() {
  19. Column() {
  20. Row() {
  21. Text('聊天精灵').textAlign(TextAlign.Center).fontSize(18)
  22. }.margin({ top: 10, bottom: 10 }).height('5%')
  23. Tabs({ barPosition: BarPosition.End, controller: this.controller, index: this.currentIndex }) {
  24. TabContent() {
  25. }.tabBar(this.TabBuilder('我的', 0, $r('app.media.chat_selected'), $r('app.media.chat_normal')))
  26. TabContent() {
  27. }.tabBar(this.TabBuilder('他的', 1, $r('app.media.others_s'), $r('app.media.others_n')))
  28. TabContent() {
  29. }.tabBar(this.TabBuilder('设置', 2, $r('app.media.setting_s'), $r('app.media.setting_n')))
  30. }
  31. .vertical(false)
  32. .height('90%')
  33. .barMode(BarMode.Fixed)
  34. .barWidth(400)
  35. .barHeight(60)
  36. .animationDuration(400)
  37. .onChange((index: number) => {
  38. this.currentIndex = index
  39. this.controller.changeIndex(this.currentIndex)
  40. })
  41. }.backgroundColor("#eeeeee")
  42. }
  43. }

最终效果如下:​

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/288963?site
推荐阅读
相关标签
  

闽ICP备14008679号