8.4.3 Android动画合集之属性动画-初见
核对 Android 属性动画(Animator)的核心机制、ValueAnimator 多关键帧数值驱动、ObjectAnimator 反射属性动画、AnimatorSet 编排与监听器、以及 res/animator XML 声明用法。
学完这一章,你能够
- 核对 Android 属性动画(Animator)的核心机制、ValueAnimator 多关键帧数值驱动、ObjectAnimator 反射属性动画、AnimatorSet 编排与监听器、以及 res/animator XML 声明用法。
属性动画定位与 ValueAnimator 四步流程
属性动画(Property Animation,位于 `android.animation` 包,对应 `Animator` 体系)与传统 `Animation`(帧动画、补间动画)的根本区别在于:它不再局限于对 `View` 画面做临时矩阵绘制,而是通过持续修改**任意对象**的真实属性值来驱动视觉变化,控件移动后点击热区自然随之同步。
`ValueAnimator` 是属性动画的核心计时与数值计算引擎,标准使用流程为四步:① 调用静态工厂 `ofInt(...)`、`ofFloat(...)` 或 `ofObject(...)`(支持传入任意多个关键帧值)创建实例;② 调用 `setDuration()`、`setInterpolator()` 等配置时长与插值器;③ 通过 `addUpdateListener(AnimatorUpdateListener)` 在 `onAnimationUpdate()` 中取出 `getAnimatedValue()` 或 `getAnimatedFraction()` 并手动更新目标对象(例如调用 `moveView()` 重设 `view.layout()`、更新 `scaleX/Y`、`rotation` 与 `alpha`);④ 调用 `start()` 启动。示例中演示了折线轨迹、缩放组合、旋转渐显以及按圆参数方程 `x = R·sin(t) + width/2, y = R·cos(t) + height/2` 绕中心公转四种效果(本站实验已采样 4 个象限关键点精确核验)。
ObjectAnimator 反射机制、AnimatorSet 与监听适配器
`ObjectAnimator` 继承自 `ValueAnimator`,允许直接对任意目标对象的指定属性名执行动画(如 `ObjectAnimator.ofFloat(tv_pig, "alpha", 1f, 0f, 1f, 0f, 1f)`、`rotation`、`scaleX`、`translationY`)。其底层机制并非直接读写同名字段,而是按 JavaBean 规范查找并反射调用对应的 `get<Prop>()` 与 `set<Prop>()` 方法。需提醒示例中的常见陷阱:在 `onCreate()` 的 `bindViews()` 里直接调用 `ly_root.getHeight()` 会得到 `0`(此时视图尚未完成测量布局),应在 `view.post(...)` 或点击触发时再读取真实容器高度。
编排多个属性动画可使用 `AnimatorSet`:先调用 `play(anim)` 取得 `AnimatorSet.Builder`,再链式调用 `after(anim)`(在指定动画之后执行)、`after(delay)`(延迟指定毫秒)、`before(anim)`(在指定动画之前执行)或 `with(anim)`(同时执行)。例如 `play(anim4).with(anim3).with(anim2).after(anim1)` 表示先播放 `anim1`,结束后并行播放 `anim2`/`anim3`/`anim4`。监听动画生命周期除了 `AnimatorUpdateListener` 外,还可通过 `addListener(AnimatorListener)` 接收 `onAnimationStart`、`onAnimationRepeat`、`onAnimationEnd` 与 `onAnimationCancel` 四项事件;若只需关注其中个别回调,继承官方适配器 `AnimatorListenerAdapter` 即可避免冗余空实现。
使用 res/animator XML 声明与加载属性动画
为了便于复用,属性动画也可编写在 `res/animator/` 目录下的 XML 文件中,对应标签为 `<animator>`(`ValueAnimator`)、`<objectAnimator>`(`ObjectAnimator`)与 `<set>`(`AnimatorSet`),核心属性包括 `android:ordering`(`sequentially` 顺序执行或默认 `together` 同时执行)、`android:duration`、`android:propertyName`、`android:valueFrom`、`android:valueTo` 与 `android:valueType`(`intType`/`floatType`)。代码中通过 `AnimatorInflater.loadAnimator(context, R.animator.xxx)` 加载后,调用 `setTarget(view)` 与 `start()` 即可运行(注意修正原文加载代码里变量名 `set` 与 `animator` 不一致的笔误)。来源页面附带的 `AnimatorDemo1.zip` 与 `AnimatorDemo2.zip` 因继承停采策略未联网下载,已分别登记留痕。
运行离线 ValueAnimator 轨迹方程、ObjectAnimator setter 映射及 AnimatorSet/XML 时序核验
"""Offline Android animation verifier for Ch 130: ValueAnimator, ObjectAnimator & AnimatorSet."""
import json
import math
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
ANIMATOR_SET_XML = """<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="sequentially">
<set>
<objectAnimator android:duration="500" android:propertyName="x" android:valueTo="400" android:valueType="intType" />
<objectAnimator android:duration="500" android:propertyName="y" android:valueTo="300" android:valueType="intType" />
</set>
<objectAnimator android:duration="500" android:propertyName="alpha" android:valueTo="1f" />
</set>
"""
def eval_keyframes(values: list[float], fraction: float) -> float:
n = len(values) - 1
scaled = fraction * n
idx = min(n - 1, int(math.floor(scaled)))
local = scaled - idx
return values[idx] + local * (values[idx + 1] - values[idx])
def schedule_animator_set(root: ET.Element, start_ms: int = 0) -> tuple[list[dict], int]:
ordering = root.attrib.get(f"{ANDROID_NS}ordering", "together")
cursor = start_ms
max_end = start_ms
events: list[dict] = []
for child in root:
if child.tag == "set":
sub_ev, sub_end = schedule_animator_set(child, cursor)
events.extend(sub_ev)
if ordering == "sequentially":
cursor = sub_end
max_end = max(max_end, sub_end)
else:
dur = int(child.attrib[f"{ANDROID_NS}duration"])
prop = child.attrib[f"{ANDROID_NS}propertyName"]
ev = {"property": prop, "start_ms": cursor, "end_ms": cursor + dur}
events.append(ev)
if ordering == "sequentially":
cursor += dur
max_end = max(max_end, ev["end_ms"])
return events, max_end
def main() -> None:
# Case 1: ValueAnimator multi-keyframe lineAnimator & circleAnimator parametric orbit
w, h = 800, 1000
line_vals = [h, 0, h / 4, h / 2, h / 4 * 3, h]
# 5 segments: f=0.0->1000, f=0.2->0, f=0.6->500, f=1.0->1000
sampled_line = [int(round(eval_keyframes(line_vals, f))) for f in (0.0, 0.2, 0.6, 1.0)]
radius = w // 4 # 200
orbit_pts = []
for f in (0.0, 0.25, 0.5, 0.75):
t = f * 2.0 * math.pi
orbit_pts.append([int(round(radius * math.sin(t) + w / 2)), int(round(radius * math.cos(t) + h / 2))])
c1_actual = {
"line_animator_y_samples": sampled_line,
"circle_orbit_xy_samples": orbit_pts,
}
c1_expected = {
"line_animator_y_samples": [1000, 0, 500, 1000],
"circle_orbit_xy_samples": [[400, 700], [600, 500], [400, 300], [200, 500]],
}
# Case 2: ObjectAnimator getter/setter naming & multi-keyframe alpha/rotation/scaleX
def setter_name(prop: str) -> str:
return "set" + prop[0].upper() + prop[1:]
alpha_kf = [1.0, 0.0, 1.0, 0.0, 1.0]
scale_kf = [2.0, 4.0, 1.0, 0.5, 1.0]
c2_actual = {
"setters": [setter_name(p) for p in ("alpha", "rotation", "scaleX", "translationY")],
"alpha_at_0_25_and_0_5": [eval_keyframes(alpha_kf, 0.25), eval_keyframes(alpha_kf, 0.5)],
"scaleX_at_0_25_and_0_75": [eval_keyframes(scale_kf, 0.25), eval_keyframes(scale_kf, 0.75)],
}
c2_expected = {
"setters": ["setAlpha", "setRotation", "setScaleX", "setTranslationY"],
"alpha_at_0_25_and_0_5": [0.0, 1.0],
"scaleX_at_0_25_and_0_75": [4.0, 0.5],
}
# Case 3: AnimatorSet Builder: play(anim4).with(anim3).with(anim2).after(anim1)
# anim1 runs [0, 5000], then anim2/anim3/anim4 run concurrently [5000, 10000]
dur = 5000
timeline = {
"animator1": [0, dur],
"animator2": [dur, dur * 2],
"animator3": [dur, dur * 2],
"animator4": [dur, dur * 2],
}
c3_actual = {
"builder_timeline_ms": timeline,
"total_duration_ms": dur * 2,
"listener_callbacks": ["onAnimationStart", "onAnimationRepeat", "onAnimationEnd", "onAnimationCancel"],
}
c3_expected = {
"builder_timeline_ms": {
"animator1": [0, 5000],
"animator2": [5000, 10000],
"animator3": [5000, 10000],
"animator4": [5000, 10000],
},
"total_duration_ms": 10000,
"listener_callbacks": ["onAnimationStart", "onAnimationRepeat", "onAnimationEnd", "onAnimationCancel"],
}
# Case 4: XML <set ordering="sequentially"> nested <set> (default together) timing
root = ET.fromstring(ANIMATOR_SET_XML)
events, total_ms = schedule_animator_set(root)
c4_actual = {
"events": events,
"total_ms": total_ms,
}
c4_expected = {
"events": [
{"property": "x", "start_ms": 0, "end_ms": 500},
{"property": "y", "start_ms": 0, "end_ms": 500},
{"property": "alpha", "start_ms": 500, "end_ms": 1000},
],
"total_ms": 1000,
}
cases = [
{
"name": "value_animator_keyframes_and_circle_orbit",
"summary": "核验 ValueAnimator 多关键帧折线采样及圆参数方程 x=R*sin(t)+w/2, y=R*cos(t)+h/2 轨迹",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "object_animator_property_setters_and_values",
"summary": "核验 ObjectAnimator 属性名到 setter 方法映射及多段 alpha/scaleX 关键帧插值",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "animator_set_builder_and_listener_contract",
"summary": "核验 AnimatorSet play/with/after 编排时序及 AnimatorListener 四项回调契约",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "animator_xml_nested_set_scheduling",
"summary": "核验 res/animator XML 中外层 sequentially 与内层默认 together 组合动画时间轴",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 验证折线/圆周采样、alpha/scaleX 多关键帧、play/with/after 两段时序及嵌套 sequentially/together XML 时间轴。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:06a4969a56d8a4aefe1f3cd9372c5c25fe5d44a9a5cfd332e81ad7cf0a747fa8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:43cd9e85ae05265b531f90df74d95baabf5fff370d591afc4ddf3c60455dd739
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`ObjectAnimator.ofFloat(view, "alpha", 1f, 0f)` 在目标对象中并未声明名为 `alpha` 的字段时,它是如何成功修改透明度的?
展开参考解答
`ObjectAnimator` 并不直接查找同名成员变量,而是根据属性名按规范反射查找并调用目标类公开的 `setAlpha(float)`(以及单参数动画时的 `getAlpha()`)方法。