Skip to content

鸿蒙tabbar ArkTS

做了仿照现在应用的做了一个tabbar。

参考文档地址

tabbar

其中有个比较重要的点是,对image资源的引用问题。

资源相关说明

图片是resources目录下的base目录下的。

media目录下的图片的资源不能添加文件夹,只能是文件,而且文件的命名规则是只能包含字母大小写和下划线。

另外{资源引用的方式](https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/ts-types-0000001477981241-V3)

要求资源定义的内容必须在编码阶段确定,中间不能更改,因此不能增加if之类的判断,只能把整个资源引用当做参数传递进去。

实现代码如下:

javascript
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  @State selectedIndex: number = 0

  @Builder TabBuider(index: number, name: string, selectedImage: Resource, normalImage: Resource) {
    Column() {
      if ( this.selectedIndex == index) {
        Image(selectedImage)
          .objectFit(ImageFit.Contain)
          .width(24)
          .height(24)
          .margin({bottom: '4lpx'})
      } else {
        Image(normalImage)
          .objectFit(ImageFit.Contain)
          .width(24)
          .height(24)
          .margin({bottom: '4lpx'})
      }

      Text(name)
        .fontSize(16)
    }
    .border({
      width: {top: '2lpx'},
      color: '#efefef',
      style: BorderStyle.Solid
    })
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  build() {
    Tabs({barPosition: BarPosition.End}) {
      TabContent() {
        Text(this.message)
      }
      .tabBar(this.TabBuider(0, "首页", $r('app.media.tabbar_home_selected'), $r('app.media.tabbar_home')))

      TabContent() {
        Text(this.message)
      }
      .tabBar(this.TabBuider(1, "数据", $r('app.media.tabbar_data_selected'), $r('app.media.tabbar_data')))

      TabContent() {
        Text(this.message)
      }
      .tabBar(this.TabBuider(2, "我的", $r('app.media.tabbar_mine_selected'), $r('app.media.tabbar_mine')))
    }.onChange(index=>{
      this.selectedIndex = index
    })
  }
}