好的,阿杰 👍
我来详细解释一下 TranslateAnimation,这是 Android 动画系统里一个比较常见的类。
1. 它是什么
- TranslateAnimation 属于 补间动画(Tween Animation),继承自
Animation
。 - 用来实现 视图的平移动画效果(即把一个 View 从某个位置移动到另一个位置)。
- 常见场景:按钮滑入滑出、图片位移、页面切换过渡等。
2. 构造方法
TranslateAnimation 提供多种构造方式,常见有:
// 方式 1:绝对像素
TranslateAnimation(float fromXDelta, float toXDelta,
float fromYDelta, float toYDelta)
// 方式 2:指定相对类型(ABSOLUTE, RELATIVE_TO_SELF, RELATIVE_TO_PARENT)
TranslateAnimation(int fromXType, float fromXValue,
int toXType, float toXValue,
int fromYType, float fromYValue,
int toYType, float toYValue)
- fromXDelta / toXDelta:X 方向的起始/结束偏移量
- fromYDelta / toYDelta:Y 方向的起始/结束偏移量
- Type 类型:
ABSOLUTE
→ 绝对坐标(以像素为单位)RELATIVE_TO_SELF
→ 相对自身宽高RELATIVE_TO_PARENT
→ 相对父容器宽高
3. 常用方法
TranslateAnimation 继承了 Animation
的一些方法,关键有:
setDuration(long duration) // 设置动画持续时间(毫秒)
setFillAfter(boolean fillAfter) // 动画结束后是否停留在最终位置
setRepeatCount(int repeatCount) // 设置重复次数
setRepeatMode(int repeatMode) // 设置重复模式(RESTART/REVERSE)
setInterpolator(Interpolator i) // 设置插值器(匀速、加速、减速等)
4. 示例代码
(1)从左到右移动 200 像素
TranslateAnimation anim = new TranslateAnimation(0, 200, 0, 0);
anim.setDuration(1000); // 1 秒
anim.setFillAfter(true); // 停在终点
myView.startAnimation(anim);
(2)相对父容器移动
TranslateAnimation anim = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, // 从父容器左边
Animation.RELATIVE_TO_PARENT, 1.0f, // 移动到父容器宽度的 100%
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
anim.setDuration(1500);
myView.startAnimation(anim);
(3)XML 定义动画(res/anim/move.xml)
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%"
android:toXDelta="100%"
android:fromYDelta="0%"
android:toYDelta="0%"
android:duration="1000"
android:fillAfter="true"/>
在 Java 代码中使用:
Animation anim = AnimationUtils.loadAnimation(this, R.anim.move);
myView.startAnimation(anim);
5. 注意事项
- 补间动画不会真正改变 View 的属性(比如 layoutX/layoutY),只是视觉上的效果。
- 如果需要真实改变位置,应使用 属性动画(ObjectAnimator/AnimatorSet)。
setFillAfter(true)
可以让动画结束后保持在目标位置,否则会回到起点。- 在复杂 UI 动效中,TranslateAnimation 更适合做“过渡效果”,属性动画更灵活。
发表回复