文章

动画面试题

动画面试题

视图动画

属性动画

动画面试题

视图动画题

可以在 onCreate 或者 onResume 中 start Animation 吗?

Android] 在 OnCreate() 中播放 Animation 动画,默认情况下,不能在 OnCreate() 中执行 animation.start(); 是无效的,因为在 OnCreate() 中 AnimationDrawable 还没有完全的与 ImageView 绑定,在 OnCreate() 中启动动画,就只能看到第一张图片。
为什么?
从 startAnimation 源码入手来看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void startAnimation(Animation animation) {
    animation.setStartTime(Animation.START_ON_FIRST_FRAME);
    setAnimation(animation);
    invalidateParentCaches();
    invalidate(true);
}
void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
	boolean fullInvalidate) {
	// ...
    final AttachInfo ai = mAttachInfo;
    final ViewParent p = mParent;
    if (p != null && ai != null && l < r && t < b) {
        final Rect damage = ai.mTmpInvalRect;
        damage.set(l, t, r, b);
        p.invalidateChild(this, damage);
    }
    // ...
}

如果 mAttachInfo 不为 null,才会执行 p.invalidateChild,而在 onCreate/onResume 中,view 还没有 attach 到 Window,mAttachInfo 为 null;而 Animation 的 applyTransformation 就是在 view 的 draw 中执行,所以在 view 还未 attach 到 Window,执行 startAnimation 是没有效果的

本文由作者按照 CC BY 4.0 进行授权