HarmonyOS onAreaChange

onAreaChange 参数两个一直相同变化,而且就算我滑动没有切换参数也会变影响取值,这个方法有替换的吗?

// xxx.ets
import { ComponentUtils } from '@kit.ArkUI'

@Entry
@Component
struct TabsExample {
  @State currentIndex: number = 0
  @State animationDuration: number = 300
  @State indicatorLeftMargin: number = 0
  @State indicatorWidth: number = 0
  private tabsWidth: number = 0
  private componentUtils: ComponentUtils = this.getUIContext().getComponentUtils()

  @Builder
  tabBuilder(index: number, name: string) {
    Column() {
      Text(name)
        .fontSize(16)
        .fontColor(this.currentIndex === index ? '#007DFF' : '#182431')
        .fontWeight(this.currentIndex === index ? 500 : 400)
        .id(index.toString())
        .onAreaChange((oldValue: Area,newValue: Area) => {
          if (this.currentIndex === index && (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.indicatorWidth = Number.isNaN(width) ? 0 : width
          }
          console.log("aaa"+newValue.width)
        })
    }.width('100%')
  }

  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      Tabs({ barPosition: BarPosition.Start }) {
        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#00CB87')
        }.tabBar(this.tabBuilder(0, 'green'))

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#007DFF')
        }.tabBar(this.tabBuilder(1, 'blue'))

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#FFBF00')
        }.tabBar(this.tabBuilder(2, 'yellow'))

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#E67C92')
        }.tabBar(this.tabBuilder(3, 'pink'))
      }
      .onAreaChange((oldValue: Area,newValue: Area)=> {
        let width = Number.parseFloat(newValue.width.toString())
        this.tabsWidth = Number.isNaN(width) ? 0 : width
      })
      .barWidth('100%')
      .barHeight(56)
      .width('100%')
      .height(296)
      .backgroundColor('#F1F3F5')
      .animationDuration(this.animationDuration)
      .onChange((index: number) => {
        this.currentIndex = index // 监听索引index的变化,实现页签内容的切换。
      })
      .onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
        // 切换动画开始时触发该回调。下划线跟着页面一起滑动,同时宽度渐变。
        this.currentIndex = 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.currentIndex = currentIndicatorInfo.index
        this.indicatorLeftMargin = currentIndicatorInfo.left
        this.indicatorWidth = currentIndicatorInfo.width
      })

      Column()
        .height(2)
        .width(this.indicatorWidth)
        .margin({ left: this.indicatorLeftMargin, top:48})
        .backgroundColor('#007DFF')
    }.width('100%')
  }

  private getTextInfo(index: number): Record<string, number> {
    let rectangle = this.componentUtils.getRectangleById(index.toString())
    return { 'left': px2vp(rectangle.windowOffset.x), 'width': px2vp(rectangle.size.width) }
  }

  private getCurrentIndicatorInfo(index: number, event: TabsAnimationEvent): Record<string, number> {
    let nextIndex = index
    if (index > 0 && event.currentOffset > 0) {
      nextIndex--
    } else if (index < 3 && 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.indicatorWidth = width
    })
  }
}
HarmonyOS
2025-01-09 16:08:10
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

根据这个demo改下吧:

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() {
                      Text(item)
                        .fontSize(16)
                        .borderRadius(5)
                        .fontSize(16)
                        .fontColor(index == this.indicatorIndex ? "#111111" : "#999999")
                        .fontWeight(index == this.indicatorIndex ? 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;
                          }
                          console.log("aaa"+newValue.width)
                        })
                        .onClick(() => {
                          this.indicatorIndex = index;
                          // 点击tabbar下划线动效
                          this.underlineScrollAuto(this.animationDuration, index);
                          this.scrollIntoView(index);
                          // 跟tabs进行联动
                          this.controller.changeIndex(index)
                        })
                    }
                    .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%')
        .margin({ top: 15, bottom: 10})

      }
      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%')
          }
          .onAreaChange((oldValue: Area, newValue: Area) => {
            let width = Number.parseFloat(newValue.width.toString());
            this.tabsWidth = Number.isNaN(width) ? 0 : width;
          })
        }, (item: string) => item)
      }
      .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%')
  }
}
分享
微博
QQ
微信
回复
2025-01-09 18:04:11
相关问题
HarmonyOS onAreaChange使用问题
1151浏览 • 1回复 待解决
HarmonyOS onAreaChange回调方法问题
541浏览 • 1回复 待解决
HarmonyOS Length 如何转换为具体数值?
718浏览 • 1回复 待解决
Canvas制作图表如何实现滑动惯性?
861浏览 • 1回复 待解决
HarmonyOS Scroll 嵌套 RelativeContainer 问题
845浏览 • 1回复 待解决
HarmonyOS Scroll嵌套RelativeContainer 问题
679浏览 • 1回复 待解决
HarmonyOS jsbridge HarmonyOS版本
382浏览 • 1回复 待解决
HarmonyOS
218浏览 • 1回复 待解决
HarmonyOS 关于HarmonyOS应用的备案
311浏览 • 1回复 待解决
HarmonyOS flutter接入HarmonyOS原生视图
526浏览 • 1回复 待解决
HarmonyOS HarmonyOS社区组件问题
664浏览 • 1回复 待解决