在HarmonyOS应用中,使用animateTo方法实现两个Column组件的属性动画时,动画未能同步执行。
问题代码如下:
import { display } from '@kit.ArkUI';
const SCREEN_WIDTH = display.getDefaultDisplaySync().width;
@Entry
@Component
struct Index {
@State translateX: number = SCREEN_WIDTH
@State lastTranslateX: number = 0
build() {
Column() {
Button('触发动画')
.onClick(() => this.startAnimation())
.margin(100)
Column() {
Text('B')
.fontSize(20)
}
.width('100%')
.height(120)
.backgroundColor('#f1f3f5')
.opacity(1)
.translate({ x: this.translateX })
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
Column() {
Text('A')
.fontSize(20)
}
.width('100%')
.height(120)
.backgroundColor('#f1f3f5')
.opacity(1)
.translate({ x: this.lastTranslateX })
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
private startAnimation() {
this.getUIContext().animateTo({
duration: 1800,
curve: Curve.EaseOut
}, () => {
this.translateX = 0
this.lastTranslateX = -SCREEN_WIDTH
})
}
} 问题效果图如下:

定义newValue状态变量,并使用onAreaChange回调方法实时获取A组件在屏幕中的实时宽度,根据组件的宽度来设置平移的数值即可。
完整代码如下所示:
@Entry
@Component
struct AnimationOutOfSync {
@State lastTranslateX: number = 0;
@State newValue: number = 0;
@State translateX: number = this.newValue;
build() {
Column() {
Button('触发动画')
.onClick(() => this.startAnimation())
.margin(100)
Column() {
Text('B')
.fontSize(20)
}
.width('100%')
.height(120)
.backgroundColor('#f1f3f5')
.translate({ x: this.translateX })
.opacity(1)
// 通过onAreaChange来获取当前组件的宽度
.onAreaChange((oldValue: Area, newValue: Area) => {
this.newValue = newValue.width as number;
this.translateX = newValue.width as number;
})
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
Column() {
Text('A')
.fontSize(20)
}
.width('100%')
.height(120)
.backgroundColor('#f1f3f5')
.translate({ x: this.lastTranslateX })
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
private startAnimation() {
this.getUIContext()?.animateTo({
duration: 1800,
curve: Curve.EaseOut
}, () => {
this.translateX = 0;
this.lastTranslateX = -this.newValue;
});
}
} 