HarmonyOS鸿蒙Next中Tab动效切换示例代码

HarmonyOS鸿蒙Next中Tab动效切换示例代码

介绍

本项目实现了点击、滑动都可实现Tab切换动效,包含文字切换。

Tab动效切换源码链接

效果预览

图片名称

使用说明

安装完成后可以通过点击、滑动查看效果。

实现思路

  1. 切换动画开始与结束时触发回调。
.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)
})
  1. 在页面跟手滑动过程中,逐帧触发该回调。
.onGestureSwipe((index: number,event: TabsAnimationEvent) => {
  let currentIndicatorInfo = this.getCurrentIndicatorInfo(index,event)
  this.currentIndex = currentIndicatorInfo.index
  this.indicatorLeftMargin = currentIndicatorInfo.left
  this.indicatorWidth = currentIndicatorInfo.width
})

更多关于HarmonyOS鸿蒙Next中Tab动效切换示例代码的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

赞,代码清晰

更多关于HarmonyOS鸿蒙Next中Tab动效切换示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,实现Tab动效切换可以通过Tabs组件和PageTransition动画结合实现。以下是一个简单的示例代码:

import { Tabs, TabContent, TabBar, Tab } from '@ohos/tabs';
import { PageTransition, PageTransitionOptions } from '@ohos/page';

@Entry
@Component
struct TabExample {
  @State currentIndex: number = 0;

  build() {
    Tabs({ index: this.currentIndex, onChange: (index) => this.currentIndex = index }) {
      TabContent() {
        Text('Tab 1 Content').fontSize(20)
      }
      TabContent() {
        Text('Tab 2 Content').fontSize(20)
      }
    }
    .onPageTransition((transition: PageTransition) => {
      transition.duration(300).ease('ease-in-out');
    })
  }
}

此代码通过Tabs组件实现Tab切换,并使用PageTransition添加平滑的过渡动画。

回到顶部