View的Detach状态对动画的影响

View的Detach状态对动画的影响

起因是在用内部是ViewPager2实现的banner控件时,每个View有浮动的动画效果,在滑动切换后,动画消失。我们都知道ViewPager2的内部是用RecyclerView来实现的,而RecyclerView复用和回收View时会将View添加和移除,第一想法是Detach对动画有影响,在实验过这个想法,开始分析

切入点

startAnimationdispatchDetachedFromWindow

源码分析

startAnimation

public void startAnimation(Animation animation) {
    animation.setStartTime(Animation.START_ON_FIRST_FRAME);
    setAnimation(animation);
    invalidateParentCaches();
    invalidate(true);
}

public void setAnimation(Animation animation) {
    mCurrentAnimation = animation;
    ...
}

可以看到只是简单给mCurrentAnimation进行了赋值,其他都是动画相关的设置,然后执行了invalidate,那么动画是怎么被执行的呢?猜测onDraw里肯定有猫腻,我们再看看另一个切入点

dispatchDetachedFromWindow

void dispatchDetachedFromWindow() {
    ...
    onDetachedFromWindowInternal();
    ...
    if (listeners != null && listeners.size() > 0) {    
        ...
        // 分发给外部回调
        for (OnAttachStateChangeListener listener : listeners) {
            listener.onViewDetachedFromWindow(this);
        }
    }
    ...
    mAttachInfo = null;
    if (mOverlay != null) {
        // 分发给Overlay
        mOverlay.getOverlayView().dispatchDetachedFromWindow();
    }
    notifyEnterOrExitForAutoFillIfNeeded(false);
}

protected void onDetachedFromWindowInternal() {
    ...
    mCurrentAnimation = null;
    ...
}

只是简单的将mCurrentAnimation置为nullonDraw的嫌疑更大了,我们追踪mCurrentAnimationusage,发现在boolean draw(Canvas canvas, ViewGroup parent, long drawingTime)中有使用,那也基本确定了我们的猜测

boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
    ...
    final Animation a = getAnimation();
    if (a != null) {
        more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
        ...
    } else {
        ...
    }
    return more;
}

private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
        Animation a, boolean scalingRequired) {
    ...
    if (!initialized) {
        ...
        onAnimationStart();
    }
    ...
    return more;
}

看到onAnimationStart我们就可以确定了,动画确实是通过onDraw来执行的,detached后,获取不到动画,也就停止了。但具体动画是怎么执行的不在讨论范围内。

你可能感兴趣的:(android动画)