HarmonyOS 如何实现首页标签滑动动效?

HarmonyOS 如何实现首页标签滑动动效?

HarmonyOS
2024-09-29 10:43:01
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

请参考如下demo:

import curves from '@ohos.curves';  
import display from '@ohos.display';  
const IS_FREE = 0;  
const IS_DRAG = 1;  
const IS_ANIMATION = 2;  
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 TabsPage {  
  private displayInfo: display.Display | null = null;  
  private swiperController: SwiperController = new SwiperController();  
  private data: MyDataSource = new MyDataSource([]);  
  private initialTabMargin: number = 5;  
  private animationDuration: number = 500;  
  private animationCurve: ICurve = curves.interpolatingSpring(7, 1, 328, 34);  
  @State swiperIndex: number = 0;  
  @State swiperWidth: number = 0; // vp  
  @State indicatorWidth: number = 0; // vp  
  @State indicatorMarginLeft: number = 0; // vp  
  @State indicatorIndex: number = 0;  
  @State indicatorSize: number = 18;  
  @State nextIndicatorIndex: number = 0;  
  @State swiperState: number = IS_FREE;  
  @State swipeRatio: number = 0;  
  private scroller: Scroller = new Scroller();  
  private arr: string[] = ['要闻', '推荐榜', '热榜', '有料小品', '娱乐', '手机', '视频', '科技树', '财经'];  
  private textLength: number[] = [2, 3, 2, 4, 2, 2, 2, 3, 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)  
  }  
  private getDisplayWidth(): number {  
    return this.displayInfo != null ? px2vp(this.displayInfo.width) : 0;  
  }  
  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 getTextFontSize(index: number): number {  
    if (this.swiperState == IS_DRAG) {  
      if (this.swiperIndex == index) {  
        return 16 + 2 * (1 - this.swipeRatio);  
      }  
      if (this.nextIndicatorIndex == index) {  
        return 16 + 2 * this.swipeRatio;  
      }  
    }  
    return this.indicatorIndex == index ? 18 : 16  
  }  
  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;  
    let indexInfo = this.getTextInfo(index);  
    let nextIndexInfo = this.getTextInfo(nextIndex);  
    this.swipeRatio = Math.abs(event.currentOffset / this.swiperWidth);  
    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;  
    const screenWidth = this.getDisplayWidth();  
    const currentOffsetX: number = this.scroller.currentOffset().xOffset;  
    this.scroller.scrollTo({  
      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);  
  }  
  build() {  
    Column() {  
      Column() {  
        Scroll(this.scroller) {  
          Row() {  
            ForEach(this.arr, (item: string, index: number) => {  
              Column() {  
                Text(item)  
                  .fontSize(this.getTextFontSize(index))// .animation({ duration: 300 })// 仅应用于fontSize  
                  .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;  
                    this.scrollIntoView(index);  
                    this.underlineScrollAuto(this.animationDuration, index);  
                    this.swiperIndex = index;  
                  })  
              }  
              .width(this.textLength[index] * 25)  
            }, (item: string) => item)  
          }  
          .height(32)  
        }  
        .width('96%')  
        .scrollable(ScrollDirection.Horizontal)  
        .scrollBar(BarState.Off)  
        .edgeEffect(EdgeEffect.Spring)  
        .onScroll((xOffset: number, yOffset: number) => {  
          console.info(xOffset + ' ' + yOffset)  
          this.indicatorMarginLeft -= xOffset;  
        })  
        .onScrollStop(() => {  
          console.info('Scroll Stop')  
          this.underlineScrollAuto(this.animationDuration, this.indicatorIndex);  
        })  
        Column()  
          .width(this.indicatorWidth)  
          .height(2)  
          .borderRadius(2)  
          .backgroundColor(Color.Red)  
          .alignSelf(ItemAlign.Start)  
          .margin({ left: this.indicatorMarginLeft, top: 5 })  
        // .animation({ duration: this.animationDuration, curve: this.animationCurve })  
      }  
      .width('100%')  
      .border({ width: { bottom: 1 }, color: 0xf1f1f1 })  
      .margin({ top: 30, bottom: 15 })  
      Swiper(this.swiperController) {  
        LazyForEach(this.data, (item: number) => {  
          Column() {  
            Text(item.toString())  
              .width('96%')  
              .height(360)  
              .borderRadius(5)  
              .backgroundColor(0xAFEEEE)  
              .textAlign(TextAlign.Center)  
              .fontSize(32)  
          }  
          .onAreaChange((oldValue: Area, newValue: Area) => {  
            let width = Number.parseFloat(newValue.width.toString());  
            this.swiperWidth = Number.isNaN(width) ? 0 : width;  
          })  
        }, (item: string) => item)  
      }  
      .onChange((index: number) => {  
        this.swiperIndex = index;  
      })  
      .cachedCount(2)  
      .index(this.swiperIndex)  
      .indicator(false)  
      .curve(this.animationCurve)  
      .loop(false)  
      .onAnimationStart((index: number, targetIndex: number, event: SwiperAnimationEvent) => {  
        // 切换动画开始时触发该回调。下划线跟着页面一起滑动,同时宽度渐变。  
        this.indicatorIndex = targetIndex;  
        this.underlineScrollAuto(this.animationDuration, targetIndex);  
        this.swiperState = IS_ANIMATION;  
      })  
      .onAnimationEnd((index: number, event: SwiperAnimationEvent) => {  
        // 切换动画结束时触发该回调。下划线动画停止。  
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event);  
        this.startAnimateTo(0, currentIndicatorInfo.left, currentIndicatorInfo.width);  
        this.scrollIntoView(index);  
        this.swiperState = IS_FREE;  
      })  
      .onGestureSwipe((index: number, event: SwiperAnimationEvent) => {  
        // 在页面跟手滑动过程中,逐帧触发该回调。  
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event);  
        this.indicatorIndex = currentIndicatorInfo.index;  
        this.indicatorMarginLeft = currentIndicatorInfo.left;  
        this.indicatorWidth = currentIndicatorInfo.width;  
        this.swiperState = IS_DRAG;  
      })  
    }  
    .width('100%')  
  }  
}
分享
微博
QQ
微信
回复
2024-09-29 18:12:56
相关问题
JS-UI 页面切面是否支持滑动动
2592浏览 • 1回复 待解决
HarmonyOS 消息首页框架实现
297浏览 • 1回复 待解决
如何实现标签随文本换行
1065浏览 • 1回复 待解决
HarmonyOS 如何实现滑动监听?
415浏览 • 1回复 待解决
怎样实现XML标签标签值的解析?
331浏览 • 1回复 待解决
HarmonyOS 如何实现滑动验证码功能
519浏览 • 1回复 待解决
HarmonyOS 首页框架问题
327浏览 • 1回复 待解决
HarmonyOS 如何读取网页中标签数据?
222浏览 • 1回复 待解决