You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Android Animation编写代码实现CSS animation-direction四类属性效果

完全可以实现,Android 系统自带的属性动画框架可以 1:1 匹配 CSS animation-direction 四个属性值的效果,具体实现说明如下:


效果对应说明

  • normal:动画始终正向播放,每次循环都从起始状态过渡到结束状态
  • reverse:动画始终反向播放,每次循环都从结束状态过渡到起始状态
  • alternate:动画奇数次正向播放、偶数次反向播放,循环时状态平滑衔接
  • alternate-reverse:动画奇数次反向播放、偶数次正向播放,循环时状态平滑衔接

实现代码

这里以实现 View 的 X 轴平移动画为例,你可以根据实际需求替换为透明度、缩放、旋转等其他属性的动画:

// 基础动画参数,可根据业务需求修改
val targetView: View = 待执行动画的视图对象
val startTranslateX = 0f // 动画正向播放的起始X偏移量
val endTranslateX = 200f // 动画正向播放的结束X偏移量
val singleAnimDuration = 300L // 单次动画执行时长,单位毫秒
val repeatCount = ValueAnimator.INFINITE // 循环次数,ValueAnimator.INFINITE代表无限循环

var animator: ObjectAnimator? = null
when (arg1) {
    "normal" -> {
        animator = ObjectAnimator.ofFloat(targetView, "translationX", startTranslateX, endTranslateX)
        animator.repeatCount = repeatCount
        animator.repeatMode = ValueAnimator.RESTART
    }
    "reverse" -> {
        animator = ObjectAnimator.ofFloat(targetView, "translationX", endTranslateX, startTranslateX)
        animator.repeatCount = repeatCount
        animator.repeatMode = ValueAnimator.RESTART
    }
    "alternate" -> {
        animator = ObjectAnimator.ofFloat(targetView, "translationX", startTranslateX, endTranslateX)
        animator.repeatCount = repeatCount
        animator.repeatMode = ValueAnimator.REVERSE
    }
    "alternate-reverse" -> {
        animator = ObjectAnimator.ofFloat(targetView, "translationX", endTranslateX, startTranslateX)
        animator.repeatCount = repeatCount
        animator.repeatMode = ValueAnimator.REVERSE
    }
}

// 启动动画
animator?.duration = singleAnimDuration
animator?.start()

多动画适配

如果需要匹配 CSS 多动画同时设置不同 animation-direction 的需求,只需要分别创建多个 Animator 实例,各自配置对应的方向参数后,放入 AnimatorSet 中同时播放即可。


内容的提问来源于stack exchange,提问作者Samet ÖZTOPRAK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:24:05