Animating drawable alpha property

 ̄綄美尐妖づ 提交于 2019-12-23 20:36:36

问题


I want to animate the alpha property of a ViewGroup's background Drawable.

I get a reference to the background's drawable using view.getBackground().

Then I use the following code (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();
        }

But the animation always starts from the alpha value 0. (meaning, when I want to animate to 0, it disappears immediately, because it animates from 0 to 0).

Does anyone know how I can make this work?


回答1:


I believe what u want is to set initial and final values for your animations, and not just the final value, like this:

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();
    }

alternatively, starting from the current value using drawable.getAlpha(), but that method is only available starting on API 19 =/



来源:https://stackoverflow.com/questions/28806879/animating-drawable-alpha-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!