【HarmonyOS NEXT】实现Tabs组件的TabBar从左到右依次排列

一、背景

系统提供的Tabs目前只能居中展示,暂不支持居左显示,现有的需求是需要Tabs从左往右排列显示,考虑通过Scroll和Row组件来实现

二、实现思路

通过Scroll和Row组件用来实现一个页签,在onclick事件中通过修改索引值和Tabs组件的索引联动,实现切换效果,同时将Tabs的barHeight置为0

三、具体实现代码

javascript 复制代码
@Entry
@Component
struct TabsComponent {
  @State tabArray: number[] = [0, 1];
  @State focusIndex: number = 0;
  private controller: TabsController = new TabsController();

  build() {
    Column() {
      // 使用自定义页签组件 
      Scroll() {
        Row() {
          ForEach(this.tabArray, (item: number, index: number) => {
            Row({ space: 20 }) {
              Text('页签' + item)
                .fontColor(index === this.focusIndex ? Color.Red : Color.Black)
                .fontWeight(index === this.focusIndex ? FontWeight.Bold : FontWeight.Normal)
            }
            .padding({ left: 10, right: 10 })
            .onClick(() => {
              this.controller.changeIndex(index);
              this.focusIndex = index;
            })
          })
        }.margin(20)
      }
      .align(Alignment.Start)
      .scrollable(ScrollDirection.Horizontal)
      .scrollBar(BarState.Off)
      .width('100%')

      //tabs组件把tabbar隐藏 
      Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
        ForEach(this.tabArray, (item: number, index: number) => {
          TabContent() {
            Text('我是页面 ' + item + " 的内容")
              .fontSize(30)
          }
        })
      }.barHeight(0)
    }
    .height('100%')
    .width('100%')
  }
}

四、实现效果

相关推荐
小雨青年10 分钟前
【鸿蒙原生开发会议随记 Pro】 会议随记 Pro v1.1 发布 详解 HarmonyOS NEXT 原生国际化(i18n)架构与最佳实践
华为·harmonyos
木斯佳1 小时前
HarmonyOS 6实战(源码教学篇)— Speech Kit TextReader:【仿某云音乐接入语音朗读控件】
华为·harmonyos
南村群童欺我老无力.2 小时前
Flutter 框架跨平台鸿蒙开发 - 校园生活一站式:打造智慧校园服务平台
flutter·华为·harmonyos
IT陈图图3 小时前
跨端一致的交互体验实践:基于 Flutter × OpenHarmony 的 AlertDialog 对话框示例解析
flutter·交互·鸿蒙·openharmony
南村群童欺我老无力.3 小时前
Flutter 框架跨平台鸿蒙开发 - 城市文创打卡:探索城市文化创意之旅
android·flutter·华为·harmonyos
yingdonglan5 小时前
Flutter 框架跨平台鸿蒙开发 ——AnimatedBuilder性能优化详解
flutter·性能优化·harmonyos
程序员清洒5 小时前
Flutter for OpenHarmony:Icon 与 IconButton — 图标系统集成
前端·学习·flutter·华为
时光慢煮5 小时前
打造跨端驾照学习助手:Flutter × OpenHarmony 实战解析
学习·flutter·华为·开源·openharmony
菜鸟小芯5 小时前
【开源鸿蒙跨平台开发先锋训练营】DAY8~DAY13 底部选项卡&首页功能实现
flutter·harmonyos
大雷神5 小时前
HarmonyOS智慧农业管理应用开发教程--高高种地-- 第19篇:语音合成 - TTS语音播报
华为·语音识别·harmonyos