鸿蒙tabbar ArkTS

本文介绍了在使用鸿蒙系统开发中,如何处理TabBar组件的选中和普通图片资源引用,强调了资源定义的固定性和编码阶段的要求。开发者需注意媒体目录图片命名规则和资源引用方式的规范。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

鸿蒙tabbar ArkTS

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

官方文档地址
参考文档

请添加图片描述

tabbar

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

资源相关说明

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

请添加图片描述

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

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

请添加图片描述

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

实现代码如下:

@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
    })
  }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xyccstudio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值