2015-03-02 81 views
1

我想动画ViewGroup背景Drawable的alpha属性。动画绘制阿尔法属性

我使用view.getBackground()获取对背景的drawable的引用。

然后我用下面的代码(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(); 
     } 

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

有谁知道我该如何做这项工作?

回答

1

我相信ü想要的是你的动画设置的初始值和最终值,而不仅仅是最终值,就像这样:

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开始=/

+1

很好的答案,但行:animator.setTarget(backgroundDrawable);是多余的,因为ofPropertyValuesHolder中的第一个参数已经定义了目标。 – yshahak 2015-06-11 16:03:10