HarmonyOS Tabs组件标题长度如何自适应

如何设置能使标题长度自适应,每个标题的间距固定,代码如下:

@Component
export struct LUACHomeMainRecommendView {
  @Prop recommendModel: LUACHTObject<LUACHTRecommendInfoData>
  @State currentIndex: number = 0

  @Builder
  tabBuilder(index: number, name?: string) {
    RelativeContainer() {
      Text(name)
        .fontColor(this.currentIndex === index ? $r('app.color.lucc_ui_color_222222') :
        $r('app.color.luac_home_tab_color_758190'))
        .fontSize(16)
        .textAlign(TextAlign.Center)
        .width('100%')
        .maxLines(1)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          middle: { anchor: '__container__', align: HorizontalAlign.Center },
          top: { anchor: '__container__', align: VerticalAlign.Top },
        })
        .margin({ top: 8 })
        .id('title')
      Image($r('app.media.luac_home_tab_progressline'))
        .width(65)
        .height(4)
        .opacity(this.currentIndex === index ? 1 : 0)
        .alignRules({
          middle: { anchor: 'title', align: HorizontalAlign.Center },
          bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
        })
        .margin({ bottom: 8 })
        .id('image')
    }
    .width('100%')
    .margin({
      top: 10,
      bottom: 0,
      left: 10,
      right: 10
    })
  }

  build() {
    Column() {
      if (this.recommendModel.data && this.recommendModel.data.length > 0) {
        Tabs({ barPosition: BarPosition.Start }) {
          ForEach(this.recommendModel.data, (item: LUACHTRecommendInfoData, index: number) => {
            TabContent() {
              Row() {
                Text(item.tabName)
                  .height(182)
                  .fontSize(20)
              }
              .backgroundColor(Color.Orange)
              .justifyContent(FlexAlign.Center)
              .width('100%')
              .height('100%')
            }.tabBar(this.tabBuilder(index, item.tabName))
          }, (item: LUACHTRecommendInfoData, index: number) => JSON.stringify(item) + index)
        }
        .vertical(false)
        .barMode(BarMode.Scrollable, { margin: 10, nonScrollableLayoutStyle: LayoutStyle.SPACE_BETWEEN_OR_CENTER })
        .fadingEdge(false)
        // .barWidth(80)
        // .barWidth('100%')
        .barHeight(44)
        .animationDuration(300)
        .onAnimationStart((index: number, targetIndex: number) => {
          this.currentIndex = targetIndex;
        })
        .width('100%')
        .height('100%')
      }
    }.width('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
HarmonyOS
2025-01-09 16:49:19
1037浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

可参考文档示例6:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-container-tabs-V5#示例6

可使用自定义tabbar,参考示例如下:

import curves from '@ohos.curves';
import display from '@ohos.display';
import { BusinessError } from '@ohos.base';
import componentUtils from '@ohos.arkui.componentUtils';


class MyDataSource implements IDataSource {
  private list: number[] = []

  constructor(list: number[]) {
    this.list = list
  }

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): number {
    return this.list[index]
  }

  registerDataChangeListener(listener: DataChangeListener): void {
  }

  unregisterDataChangeListener() {
  }
}

@Entry
@Component
struct swiperTab {
  private displayInfo: display.Display | null = null;
  private controller: TabsController = new TabsController()
  private data: MyDataSource = new MyDataSource([]);
  private initialTabMargin: number = 5; //初始化时tabbarmargin
  private animationDuration: number = 300; //动画时间
  private animationCurve: ICurve = curves.interpolatingSpring(7, 1, 328, 34); //动画曲线
  @State currentIndex: number = 0; //内容区当前Index
  @State tabsWidth: number = 0; // vp 内容区宽度
  @State indicatorWidth: number = 0; // vp 页签宽度
  @State indicatorMarginLeft: number = 5; // vp 当前页签距离左边margin
  @State indicatorIndex: number = 0; //当前页签Index
  @State nextIndicatorIndex: number = 0; //下一个目标页签Index
  @State swipeRatio: number = 0; //判断是否翻页,页面滑动超过一半,tabBar切换到下一页。
  private scroller: Scroller = new Scroller();
  private arr: string[] = ['关注', '推荐', '热点', '上海', '视频', '新时代', '新歌', '新碟', '新片'];
  private textLength: number[] = [2, 2, 2, 2, 2, 3, 2, 2, 2,] // 控制页签所在父容器宽度,避免造成下划线目标位置计算错误

  aboutToAppear(): void {
    this.displayInfo = display.getDefaultDisplaySync(); //获取屏幕实例
    let list: number[] = [];
    for (let i = 1; i <= this.arr.length; i++) {
      list.push(i);
    }
    this.data = new MyDataSource(list)
  }

  // 获取屏幕宽度,单位vp
  private getDisplayWidth(): number {
    return this.displayInfo != null ? px2vp(this.displayInfo.width) : 0;
  }

  // 获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。
  private getTextInfo(index: number): Record<string, number> {
    let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById(index.toString());
    try {
      return { 'left': px2vp(modePosition.windowOffset.x), 'width': px2vp(modePosition.size.width) }
    } catch (error) {
      return { 'left': 0, 'width': 0 }
    }
  }

  // 当前下划线动画
  private getCurrentIndicatorInfo(index: number, event: SwiperAnimationEvent): Record<string, number> {
    let nextIndex = index;
    // 滑动范围限制,Swiper不可循环,Scroll保持不可循环
    if (index > 0 && event.currentOffset > 0) {
      nextIndex--; // 左滑
    } else if (index < this.data.totalCount() - 1 && event.currentOffset < 0) {
      nextIndex++; // 右滑
    }
    this.nextIndicatorIndex = nextIndex;
    // 获取当前tabbar的属性信息
    let indexInfo = this.getTextInfo(index);
    // 获取目标tabbar的属性信息
    let nextIndexInfo = this.getTextInfo(nextIndex);
    // 滑动页面超过一半时页面切换
    this.swipeRatio = Math.abs(event.currentOffset / this.tabsWidth);
    let currentIndex = this.swipeRatio > 0.5 ? nextIndex : index; // 页面滑动超过一半,tabBar切换到下一页。
    let currentLeft = indexInfo.left + (nextIndexInfo.left - indexInfo.left) * this.swipeRatio;
    let currentWidth = indexInfo.width + (nextIndexInfo.width - indexInfo.width) * this.swipeRatio;
    this.indicatorIndex = currentIndex;
    return { 'index': currentIndex, 'left': currentLeft, 'width': currentWidth };
  }

  private scrollIntoView(currentIndex: number): void {
    const indexInfo = this.getTextInfo(currentIndex);
    let tabPositionLeft = indexInfo.left;
    let tabWidth = indexInfo.width;
    // 获取屏幕宽度,单位vp
    const screenWidth = this.getDisplayWidth();
    const currentOffsetX: number = this.scroller.currentOffset().xOffset; //当前滚动的偏移量
    this.scroller.scrollTo({
      // 将tabbar可滑动时候定位在正中间
      xOffset: currentOffsetX + tabPositionLeft - screenWidth / 2 + tabWidth / 2,
      yOffset: 0,
      animation: {
        duration: this.animationDuration,
        curve: this.animationCurve, // 动画曲线
      }
    });
    this.underlineScrollAuto(this.animationDuration, currentIndex);
  }

  private startAnimateTo(duration: number, marginLeft: number, width: number): void {
    animateTo({
      duration: duration, // 动画时长
      curve: this.animationCurve, // 动画曲线
      onFinish: () => {
        console.info('play end')
      }
    }, () => {
      this.indicatorMarginLeft = marginLeft;
      this.indicatorWidth = width;
    })
  }

  // 下划线动画
  private underlineScrollAuto(duration: number, index: number): void {
    let indexInfo = this.getTextInfo(index);
    this.startAnimateTo(duration, indexInfo.left, indexInfo.width);
  }

  getStringFromResource(source: Resource): string {
    try {
      getContext(this).resourceManager.getStringSync(source.id);
      let str = getContext(this).resourceManager.getStringSync(source.id);
      return str
    } catch (error) {
      let code = (error as BusinessError).code;
      let message = (error as BusinessError).message;
      console.error(`getStringSync failed, error code: ${code}, message: ${message}.`);
      return ''
    }
  }

  build() {
    Column() {
      // tabbar
      Row() {
        Column() {
          Scroll() {
            Column() {
              Scroll(this.scroller) {
                Row() {
                  ForEach(this.arr, (item: string, index: number) => {
                    Column() {
                      if (index === 2 || index === 4) {
                        Image($r('app.media.1'))
                          .height(50)
                          .width(50)
                          .id(index.toString())
                          .onAreaChange((oldValue: Area, newValue: Area) => {
                            if (this.indicatorIndex === index &&
                              (this.indicatorMarginLeft === 0 || this.indicatorWidth === 0)) {
                              if (newValue.globalPosition.x != undefined) {
                                let positionX = Number.parseFloat(newValue.globalPosition.x.toString());
                                this.indicatorMarginLeft = Number.isNaN(positionX) ? 0 : positionX;
                              }
                              let width = Number.parseFloat(newValue.width.toString());
                              this.indicatorWidth = Number.isNaN(width) ? 0 : width;
                            }
                          })
                      } else {
                        Text(item)
                          .fontSize(16)
                          .borderRadius(5)
                          .fontColor(this.indicatorIndex === index ? Color.Red : Color.Black)
                          .fontWeight(this.indicatorIndex === index ? FontWeight.Bold : FontWeight.Normal)
                          .margin({ left: this.initialTabMargin, right: this.initialTabMargin })
                          .id(index.toString())
                          .onAreaChange((oldValue: Area, newValue: Area) => {
                            if (this.indicatorIndex === index &&
                              (this.indicatorMarginLeft === 0 || this.indicatorWidth === 0)) {
                              if (newValue.globalPosition.x != undefined) {
                                let positionX = Number.parseFloat(newValue.globalPosition.x.toString());
                                this.indicatorMarginLeft = Number.isNaN(positionX) ? 0 : positionX;
                              }
                              let width = Number.parseFloat(newValue.width.toString());
                              this.indicatorWidth = Number.isNaN(width) ? 0 : width;
                            }
                          })
                          .onClick(() => {
                            this.indicatorIndex = index;
                            // 点击tabbar下划线动效
                            this.underlineScrollAuto(this.animationDuration, index);
                            this.scrollIntoView(index);
                            // 跟tabs进行联动
                            this.controller.changeIndex(index)
                          })
                      }
                    }
                    .margin(10)
                    .width(this.textLength[index] * 28)
                  }, (item: string) => item)
                }
                .height(32)
              }
              .width('100%')
              .scrollable(ScrollDirection.Horizontal)
              .scrollBar(BarState.Off)
              .edgeEffect(EdgeEffect.None)
              // 滚动事件回调, 返回滚动时水平、竖直方向偏移量
              .onScroll((xOffset: number, yOffset: number) => {
                console.info(xOffset + ' ' + yOffset)
                this.indicatorMarginLeft -= xOffset;
              })
              // 滚动停止事件回调
              .onScrollStop(() => {
                console.info('Scroll Stop')
                this.underlineScrollAuto(0, this.indicatorIndex);
              })

              Column()
                .width(this.indicatorWidth)
                .height(2)
                .borderRadius(2)
                .backgroundColor(Color.Red)
                .alignSelf(ItemAlign.Start)
                .margin({ left: this.indicatorMarginLeft, top: 5 })
            }
          }
        }
        .width('100%')
      }

      Tabs({ controller: this.controller }) {
        LazyForEach(this.data, (item: number, index: number) => {
          TabContent() {
            List({ space: 10 }) {
              ListItem() {
                Text(item.toString())
              }
            }
            .padding({ left: 10, right: 10 })
            .width("100%")
            .height('95%')
          }
          .backgroundColor(Color.Red)
          .onAreaChange((oldValue: Area, newValue: Area) => {
            let width = Number.parseFloat(newValue.width.toString());
            this.tabsWidth = Number.isNaN(width) ? 0 : width;
          })
        }, (item: string) => item)
      }
      .barHeight(0)
      .onChange((index: number) => {
        this.currentIndex = index;
      })

      .onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
        // 切换动画开始时触发该回调。下划线跟着页面一起滑动,同时宽度渐变。
        this.indicatorIndex = targetIndex;
        this.underlineScrollAuto(this.animationDuration, targetIndex);
      })
      .onAnimationEnd((index: number, event: TabsAnimationEvent) => {
        // 切换动画结束时触发该回调。下划线动画停止。
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event);
        this.startAnimateTo(0, currentIndicatorInfo.left, currentIndicatorInfo.width);
        this.scrollIntoView(index);
      })
      .onGestureSwipe((index: number, event: TabsAnimationEvent) => {
        // 在页面跟手滑动过程中,逐帧触发该回调。
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event);
        this.indicatorIndex = currentIndicatorInfo.index; //当前页签index
        this.indicatorMarginLeft = currentIndicatorInfo.left; //当前页签距离左边margin
        this.indicatorWidth = currentIndicatorInfo.width; //当前页签宽度
      })
    }
    .width('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
  • 258.
  • 259.
  • 260.
  • 261.
  • 262.
  • 263.
  • 264.
  • 265.
  • 266.
  • 267.
  • 268.
  • 269.
  • 270.
  • 271.
  • 272.
  • 273.
  • 274.
  • 275.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280.
  • 281.
  • 282.
分享
微博
QQ
微信
回复
2025-01-09 18:39:37
相关问题
Web组件如何实现高度自适应
1746浏览 • 1回复 待解决
Grid组件如何实现高度自适应
4164浏览 • 1回复 待解决
HarmonyOS web组件怎么自适应高度
754浏览 • 1回复 待解决
HarmonyOS Grid组件能否高度自适应
769浏览 • 1回复 待解决
HarmonyOS 自适应组件高度问题
1870浏览 • 1回复 待解决
HarmonyOS web组件自适应高度问题
1803浏览 • 1回复 待解决
HarmonyOS Grid组件能否自适应内容高度?
673浏览 • 1回复 待解决
HarmonyOS RichText自适应高度
758浏览 • 1回复 待解决
HarmonyOS Text无法自适应
622浏览 • 1回复 待解决
arktsUI组件自适应要怎么?
1186浏览 • 1回复 待解决
HarmonyOS grid如何自适应宽度
854浏览 • 1回复 待解决
HarmonyOS webview如何设置自适应
1423浏览 • 1回复 待解决
HarmonyOS 高度自适应
1052浏览 • 1回复 待解决
HarmonyOS 如何实现自适应web的高度
641浏览 • 1回复 待解决
HarmonyOS RelativeContainer无法自适应高度
1268浏览 • 1回复 待解决
HarmonyOS RichText能否自适应高度
652浏览 • 1回复 待解决
HarmonyOS Web高度自适应问题
1604浏览 • 1回复 待解决