动画绘图可绘制对象的透明度属性

5
我想要对ViewGroup背景的Drawable的alpha属性进行动画处理。
我可以通过view.getBackground()获取背景的drawable引用。
然后我使用以下代码(取自此帖子):
    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)。

有人知道我该如何解决这个问题吗?

1个回答

6
我相信您想要为动画设置初始值和最终值,而不仅仅是最终值,例如以下方式:

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

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及以上版本可用 = /


3
回答很好,但是这一行代码:animator.setTarget(backgroundDrawable); 是多余的,因为 ofPropertyValuesHolder 的第一个参数已经定义了目标。 - yshahak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接