鸿蒙HarmonyOS之使用ArkTs语言实现自定义Tab菜单栏分页主页面UI

一、效果

显示为3个Tab菜单栏,中间可以滑动

二、实现步骤

1、Index.ets

示例代码中用到的颜色、文字、图片等资源可以自行替换

复制代码
import { Tab_1 } from './Tab_1';
import { Tab_2 } from './Tab_2';
import { Tab_3 } from './Tab_3';


//主页面
@Entry
@Component
struct Index {

  @State tabsIndex: number = 0;

  build() {
    //barPosition为End,vertical为false是底部导航
    Tabs({ barPosition: BarPosition.End }) {
      //tab1
      TabContent(){
        Tab_1()
      }
      .tabBar(this.TabBarBuilder(0,$r("app.media.ic_select_live"),$r("app.media.ic_unselect_live"),$r('app.string.tab_live')))

      //tab2
      TabContent(){
        Tab_2()
      }
     .tabBar(this.TabBarBuilder(1,$r("app.media.ic_select_cloud_upload"),$r("app.media.ic_unselect_cloud_upload"),$r('app.string.tab_cloud_upload')))

      //tab3
      TabContent(){
        Tab_3()
      }
      .tabBar(this.TabBarBuilder(2,$r("app.media.ic_select_setting"),$r("app.media.ic_unselect_setting"),$r('app.string.tab_setting')))
    }
    //barMode是控制导航菜单栏是否可以滚动,默认值为Fixed:固定导航栏
    .barMode(BarMode.Fixed)
    .barHeight(56)
    .barWidth('100%')
    .vertical(false)
    .backgroundColor($r('app.color.background_shallow_grey'))
    .onChange((index: number) => {
      //记录当前选中Tab页签位置
      this.tabsIndex = index;
    })
  }


  /**
   * 自定义导航栏tab组件样式
   * @param index 页签对应位置
   * @param selectedImage 选中状态图片资源
   * @param unselectedImage 未选中状态图片资源
   * @param tabBarName tab栏名称
   */
  @Builder
  TabBarBuilder(index: number, selectedImage: Resource, unselectedImage: Resource, tabBarName: Resource) {
    Column() {
      Image(this.tabsIndex === index ? selectedImage : unselectedImage)
        .width(24)
        .height(24)
        .margin({ bottom: 4 })

      Text(tabBarName)
        .fontSize(10)
        .fontFamily('HarmonyHeiTi-Medium')
        .fontColor(this.tabsIndex === index ? $r('app.color.tab_bar_select') : $r('app.color.tab_bar_unselect'))
    }
    .width('100%')
    .padding({ top: 6, bottom: 6 })
    .alignItems(HorizontalAlign.Center)
    .id(`tabBar${index}`)
  }
}

2、分别创建Tab_1、Tab_2、Tab_3的ArkTs页

示例:每个Tab页面内容可以在各自的ArkTs文件里面编写

复制代码
@Preview
@Component
export struct Tab_1 {

  build(){
    Row(){
      Text($r('app.string.tab_setting'))
        .fontSize(20)
        .fontFamily('HarmonyHeiTi-Medium')
        .fontColor($r('app.color.tab_bar_select'))
    }
    .width('100%')
    .height('100%')
  }
}

3、预览查看Index.ets即可查看效果

相关推荐
城中的雾41 分钟前
HarmonyOS应用拉起系列(三):如何直接拉起腾讯/百度/高德地图进行导航
前端·javascript·harmonyos
程序员潘Sir2 小时前
鸿蒙应用开发从入门到实战(七):ArkTS组件声明语法
harmonyos·鸿蒙
高心星18 小时前
鸿蒙5.0项目开发——V2装饰器@Event的使用
harmonyos
ChinaDragon19 小时前
HarmonyOS:创建ArkTS卡片
harmonyos
高心星19 小时前
HarmonyOS 5.0应用开发——V2装饰器@once的使用
harmonyos
程序员潘Sir1 天前
鸿蒙应用开发从入门到实战(六):ArkTS声明式UI和组件化
harmonyos·鸿蒙
猫林老师1 天前
HarmonyOS数据持久化:Preferences轻量级存储实战
华为·harmonyos
Yasin Chen1 天前
Unity UI坐标说明
ui·unity