鸿蒙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即可查看效果

相关推荐
鸿蒙先行者22 分钟前
鸿蒙ArkUI布局与性能优化技术探索
harmonyos·arkui
威哥爱编程39 分钟前
鸿蒙 NEXT开发中轻松实现人脸识别功能
harmonyos
用户8054707368121 小时前
【鸿蒙开发教程】HarmonyOS 实现List 列表
harmonyos
小喷友6 小时前
第4章 数据与存储
前端·app·harmonyos
CodeCraft Studio21 小时前
在 Python 中操作 Excel 文件的高效方案 —— Aspose.Cells for Python
python·ui·excel·报表·aspose·aspose.cells
小小小小小星1 天前
鸿蒙开发核心功能模块全解析:从架构到实战应用
harmonyos
奶糖不太甜1 天前
鸿蒙开发问题之纯血鸿蒙自启动步骤详解
harmonyos
xq95271 天前
鸿蒙next 获取versionCode和versionName
harmonyos
鸿蒙小白龙1 天前
openharmony之恢复出厂设置需求总结
harmonyos·鸿蒙·鸿蒙系统
深海的鲸同学 luvi1 天前
【HarmonyOS】H5 实现在浏览器中正常跳转 AppLinking 至应用
华为·harmonyos