Android 中的平移动画详解文档

一、什么是平移动画?

平移动画是 Android 中的一种基础动画效果,它允许你在屏幕上沿 X 或 Y 方向移动视图(View),不改变视图本身的布局属性,仅仅是“看起来”被移动了。

平移的本质是对 View 的 translationXtranslationY 属性进行动态设置,单位是像素(px),通过动画的方式实现流畅的移动效果。

二、实现方式

1. 使用 ViewPropertyAnimator(简洁高效)

1
2
3
4
view.animate()
.translationY(100f)
.setDuration(300)
.start()
  • translationX()translationY() 控制平移位置(相对初始位置)
  • setDuration() 设置动画时间,单位毫秒
  • start() 开始动画

2. 使用 ObjectAnimator(更灵活)

1
2
3
4
5
ObjectAnimator.ofFloat(view, "translationY", 0f, 100f).apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
start()
}
  • 可以用于组合动画(如配合透明度等)
  • 支持设置插值器(Interpolator)控制动画节奏

3. 使用 XML 动画资源(解耦代码)

创建一个 res/anim/translate.xml 文件:

1
2
3
4
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromYDelta="0"
android:toYDelta="100" />

然后在代码中使用:

1
2
val animation = AnimationUtils.loadAnimation(context, R.anim.translate)
view.startAnimation(animation)

注意:XML 平移动画仅用于视觉效果,不会改变 translationX/Y 的实际属性值。

三、translationX 和 translationY 属性解释

  • translationX: 控制视图在水平方向的平移距离(+ 右移,- 左移)
  • translationY: 控制视图在垂直方向的平移距离(+ 下移,- 上移)

示例:

1
android:translationY="-20dp"

表示该视图在绘制时整体向上偏移 20dp,注意:这是视觉偏移,View 的布局位置未变。

四、常见动画组合使用

1. 平移 + 淡入淡出:

1
2
3
4
5
6
val animatorSet = AnimatorSet()
val translate = ObjectAnimator.ofFloat(view, "translationY", 0f, -100f)
val fade = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f)
animatorSet.playTogether(translate, fade)
animatorSet.duration = 300
animatorSet.start()

2. 平移 + 缩放:

1
2
3
4
5
6
7
8
9
AnimatorSet().apply {
playTogether(
ObjectAnimator.ofFloat(view, "translationX", 0f, 200f),
ObjectAnimator.ofFloat(view, "scaleX", 1f, 1.2f),
ObjectAnimator.ofFloat(view, "scaleY", 1f, 1.2f)
)
duration = 500
start()
}

五、应用场景

  • 页面元素的自然入场 / 退出动画(如 Banner 切换)
  • 提示框、抽屉菜单滑出 / 收回
  • RecyclerView 中 item 动画
  • 悬浮按钮、弹窗等交互动画

六、注意事项

  1. 布局未改变:使用 translationX/Y 不会改变 View 的实际布局边界,仅是视觉上的移动。
  2. 单位转换:ObjectAnimator 里的数值是 px,需从 dp 转换。例如:
1
2
val px = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 20f, context.resources.displayMetrics)
  1. 动画冲突处理:动画尚未结束时开始新动画可能导致错位,建议使用 .cancel() 清除旧动画。
  2. 点击区域未改变:由于布局位置未变,点击区域不随动画变化而变化(可用 View.setOnTouchListener 做处理)。

七、补充建议

  • 若需要更真实的运动感,可以尝试使用 物理动画 API(SpringAnimation)实现带阻尼的平移。
  • 使用 ViewPropertyAnimator 性能更好,适合处理频繁动画。
  • Android 12+ 可结合 Transition 框架使用 Slide 类简化界面切换的平移动画。

如需进一步学习,可以结合 MotionLayout 使用平移动画,支持关键帧控制与复杂动画协调。

如需补充具体场景(如 RecyclerView item 动画)、结合 MotionLayout 的平移使用,或配合 BottomSheet 的使用,请告诉我。