动画可绘制 alpha 属性

Animating drawable alpha property

我想为 ViewGroup 的背景 Drawable 的 alpha 属性 设置动画。

我使用 view.getBackground() 获得对背景可绘制对象的引用。

然后我使用下面的代码(from this thread):

    if (backgroundDrawable.getAlpha() == 0) {
            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(backgroundDrawable, PropertyValuesHolder.ofInt("alpha", 255));
            animator.setTarget(backgroundDrawable);
            animator.setDuration(2000);
            animator.start();
        } else {
            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(backgroundDrawable, PropertyValuesHolder.ofInt("alpha", 0));
            animator.setTarget(backgroundDrawable);
            animator.setDuration(2000);
            animator.start();
        }

但是动画总是从 alpha 值 0 开始。(意思是,当我想动画到 0 时,它会立即消失,因为它是从 0 到 0 动画)。

有谁知道我该怎么做?

我相信您想要的是为动画设置初始值和最终值,而不仅仅是最终值,如下所示:

if (backgroundDrawable.getAlpha() == 0) {
        ObjectAnimator animator = ObjectAnimator
            .ofPropertyValuesHolder(backgroundDrawable, 
                      PropertyValuesHolder.ofInt("alpha", 0, 255));
        animator.setTarget(backgroundDrawable);
        animator.setDuration(2000);
        animator.start();
    } else {
        ObjectAnimator animator = ObjectAnimator
             .ofPropertyValuesHolder(backgroundDrawable, 
                       PropertyValuesHolder.ofInt("alpha", 255, 0));
        animator.setTarget(backgroundDrawable);
        animator.setDuration(2000);
        animator.start();
    }

或者,使用 drawable.getAlpha() 从当前值开始,但该方法仅适用于 API 19 =/