动画可绘制的alpha属性

dor*_*ors 3 android android-animation

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

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

然后,我使用以下代码(来自此线程):

    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();
        }
Run Code Online (Sandbox Code Playgroud)

但是动画总是从alpha值0开始。(意味着,当我想将动画设置为0时,它会立即消失,因为它是从0到0进行动画处理)。

有谁知道我该怎么做?

Bud*_*ius 5

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

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();
    }
Run Code Online (Sandbox Code Playgroud)

或者,使用从当前值开始drawable.getAlpha(),但是该方法仅在API 19 = /上可用。

  • 很好的答案,但是这行:animator.setTarget(backgroundDrawable); 是多余的,因为ofPropertyValuesHolder中的第一个参数已经定义了目标。 (2认同)