HarmonyOS 鸿蒙Next中Tabs组件能否设置一个固定在最右边的按钮

HarmonyOS 鸿蒙Next中Tabs组件能否设置一个固定在最右边的按钮 Tabs组件设置为滚动模式,能否设置一个一直固定在最右边的按钮

3 回复

可参考以下demo:

@Entry
@Component

struct tabTest {

  @State tabArray: Array<number> = [0, 1, 2, 3, 4]
  @State focusIndex: number = 0
  @State index: number = 0
  private controller: TabsController = new TabsController()
  @State test: boolean = false
  @State animationDuration: number = 300
  @State indicatorLeftMargin: number = 0
  @State indicatorWidth: number = 0
  private tabsWidth: number = 0
  private tabWidth: number = 0;
  private scrollerForScroll: Scroller = new Scroller()

  // 单独的页签
  @Builder
  Tab(tabName: string, tabItem: number, tabIndex: number) {
    Row({ space: 20 }) {
      Text(tabName)
        .fontSize(18)
        .fontColor(tabIndex === this.focusIndex ? Color.Blue : Color.Black)
        .id(tabIndex.toString())
        .onAreaChange((oldValue: Area, newValue: Area) => {
          if (this.focusIndex === tabIndex && (this.indicatorLeftMargin === 0 || this.indicatorWidth === 0)){
            if (newValue.position.x != undefined) {
              let positionX = Number.parseFloat(newValue.position.x.toString())
              this.indicatorLeftMargin = Number.isNaN(positionX) ? 0 : positionX
            }
            let width = Number.parseFloat(newValue.width.toString())
            this.tabWidth = Number.isNaN(width) ? 0 : width
            this.indicatorWidth = this.tabWidth
          }
        })
    }
    .justifyContent(FlexAlign.Center)
    .constraintSize({ minWidth: 35 })
    .width(100)
    .height(30)
    .onClick(() => {
      this.controller.changeIndex(tabIndex)
      this.focusIndex = tabIndex
    })
    .backgroundColor("#ffb7b7b7")
  }

  @Builder
  textTest(textName: string){
    Row({ space: 20 }) {
      Text(textName).fontSize(18)
    }
    .justifyContent(FlexAlign.Center)
    .constraintSize({ minWidth: 35 })
    .height(30)
    .backgroundColor("#ffb7b7b7")
  }

  build() {
    Column() {
      Stack({ alignContent: Alignment.TopStart }) {
        Column() {
          // 页签
          Row({ space: 8 }) {
            List({ space: 20, initialIndex: 0, scroller: this.scrollerForScroll }) {
              ForEach(this.tabArray, (item: number, index: number) => {
                ListItem() {
                  this.Tab("页签 " + item, item, index)
                }
              }, (item: string) => item)
            }
            .listDirection(Axis.Horizontal)
            .height(30)
            .width('80%')
            .friction(0.6)
            .alignListItem(ListItemAlign.Start)
            .scrollBar(BarState.Off)
            .width('80%')
            .backgroundColor("#ffb7b7b7")
            .onScroll((xOffset: number, yOffset: number) => {
              this.indicatorLeftMargin -= xOffset
            })
            this.textTest('更多')
          }
          .alignItems(VerticalAlign.Bottom)
          .width('100%')
          .backgroundColor("#ffb7b7b7")

        }
        .alignItems(HorizontalAlign.Start)
        .width('100%')
        .Column()
        .height(2)
        .width(this.indicatorWidth)
        .margin({ left: this.indicatorLeftMargin, top: 30})
        .backgroundColor(Color.Blue)

      }
      .height(40)
      .width('100%')
      .backgroundColor("#ffb7b7b7")

      //tabs
      Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
        ForEach(this.tabArray, (item: number, index: number) => {
          TabContent() {
            Text('我是页面 ' + item + " 的内容")
              .height(300)
              .width('100%')
              .fontSize(30)
          }
          .backgroundColor(Color.White)
        }, (item: string) => item)
      }
      .onAreaChange((oldValue: Area, newValue: Area) => {
        let width = Number.parseFloat(newValue.width.toString())
        this.tabsWidth = Number.isNaN(width) ? 0 : width
      })
      .width('100%')
      .barHeight(0)
      .animationDuration(100)
      .onChange((index: number) => {
        console.log('foo change')
        this.focusIndex = index
        this.scrollerForScroll.scrollToIndex(index-1, true)
      })
      .onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
        // 切换动画开始时触发该回调。下划线跟着页面一起滑动
        this.focusIndex = targetIndex
        let targetIndexInfo = this.getTextInfo(targetIndex)
        this.startAnimateTo(this.animationDuration, targetIndexInfo.left, targetIndexInfo.width)
      })
      .onAnimationEnd((index: number, event: TabsAnimationEvent) => {
        // 切换动画结束时触发该回调。下划线动画停止。
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
        this.startAnimateTo(0, currentIndicatorInfo.left, currentIndicatorInfo.width)
      })
      .onGestureSwipe((index: number, event: TabsAnimationEvent) => {
        // 在页面跟手滑动过程中,逐帧触发该回调。
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
        this.focusIndex = currentIndicatorInfo.index
        this.indicatorLeftMargin = currentIndicatorInfo.left
        this.tabWidth = currentIndicatorInfo.width
        this.indicatorWidth = currentIndicatorInfo.width
      })
    }
    .height('100%')
  }

  private getTextInfo(index: number): Record<string, number> {
    let strJson = getInspectorByKey(index.toString())
    try {
      let obj: Record<string, string> = JSON.parse(strJson)
      let rectInfo: number[][] = JSON.parse('[' + obj.$rect + ']')
      return { 'left': px2vp(rectInfo[0][0]), 'width': px2vp(rectInfo[1][0] - rectInfo[0][0]) }
    } catch (error) {
      return { 'left': 0, 'width': 0 }
    }
  }

  private getCurrentIndicatorInfo(index: number, event: TabsAnimationEvent): Record<string, number> {
    let nextIndex = index
    if (index > 0 && event.currentOffset > 0) {
      nextIndex--
    } else if (index < 4 && event.currentOffset < 0) {
      nextIndex++
    }
    let indexInfo = this.getTextInfo(index)
    let nextIndexInfo = this.getTextInfo(nextIndex)
    let swipeRatio = Math.abs(event.currentOffset / this.tabsWidth)
    let currentIndex = swipeRatio > 0.5 ? nextIndex : index // 页面滑动超过一半,tabBar切换到下一页。
    let currentLeft = indexInfo.left + (nextIndexInfo.left - indexInfo.left) * swipeRatio
    let currentWidth = indexInfo.width + (nextIndexInfo.width - indexInfo.width) * swipeRatio
    return { 'index': currentIndex, 'left': currentLeft, 'width': currentWidth }
  }

  private startAnimateTo(duration: number, leftMargin: number, width: number) {
    animateTo({
      duration: duration, // 动画时长
      curve: Curve.Linear, // 动画曲线
      iterations: 1, // 播放次数
      playMode: PlayMode.Normal, // 动画模式
      onFinish: () => {
        console.info('play end')
      }
    }, () => {
      this.indicatorLeftMargin = leftMargin
      this.tabWidth = width
      this.indicatorWidth = width
    })
  }
}

更多关于HarmonyOS 鸿蒙Next中Tabs组件能否设置一个固定在最右边的按钮的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,Tabs组件目前不支持直接设置一个固定在最右边的按钮。Tabs组件主要用于实现标签页切换功能,默认布局是标签页水平排列,不支持在右侧添加固定按钮。如果你需要在页面右侧添加按钮,可以考虑在Tabs组件外部使用其他布局组件,如Row或Column,将Tabs组件与按钮组合在一起,通过自定义布局实现类似效果。

在HarmonyOS的鸿蒙Next中,Tabs组件本身不支持直接设置一个固定在最右边的按钮。但你可以通过自定义布局实现这一需求。可以在Tabs组件外部使用RowColumn布局,将Tabs组件和一个按钮放置在同一行,通过设置按钮的layoutWeightalign属性,使其固定在右边。例如:

<Row>
    <Tabs>
        <TabContent ... />
    </Tabs>
    <Button
        text="按钮"
        layout_weight="1"
        align="right" />
</Row>
回到顶部