2015-03-02 70 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