讓界面動起來!屬性動畫淺談!

目錄

  • 前言

  • ObjectAnimator的初步使用

  • 用AnimatorSet進行動畫混合

  • 將動畫寫在xml中

  • 動畫監聽

  • 最後


前言

屬性動畫是非常非常好用的, 谷歌自己都說這是一個強大的框架. 那今天就來了解一下它.

ObjectAnimator的初步使用

屬性動畫最大的特點就是可以讓任何Object動起來, 我先給個小栗子, 大家感受一下.

TextView tvTest = (TextView) findViewById(R.id.tv_test);float curTranslationY = tvTest.getTranslationY();ObjectAnimator animator = ObjectAnimator.ofFloat(tvTest, "translationY", curTranslationY, curTranslationY + 100f);animator.setDuration(2000);animator.start(); 

讓界面動起來!屬性動畫淺談!

給我動!

屬性動畫有個很重要的點就是說, 動畫過後, 控件本身真的就變換了, 而不單單是繪製出了效果.

然後這裡ofFloat()
函數的第一個參數自然是控件了, 第二個參數是可以填入很多的, 比如"alpha", "rotation", 到底有多少, 大家可以移步官方文檔, 之前已經貼出了. 然後後面的參數根據第二個參數來, 可多個, 這裡可能說的不太清晰, 所以我們再來一個小栗子.

TextView tvTest = (TextView) findViewById(R.id.tv_test);ObjectAnimator animator = ObjectAnimator.ofFloat(tvTest, "alpha", 1f, 0f, 1f, 0f, 1f, 0f, 1f);animator.setDuration(2000);animator.start();

讓界面動起來!屬性動畫淺談!

給我動!


用AnimatorSet進行動畫混合

一般來說, 讓人感覺舒服的動畫都不會是單一變換的動畫, 肯定要各種動畫混合一起, 來達到某種效果. 我這裡進行一些混合的嘗試, 順便再展示幾種動畫.

// 垂直移動float curTranslationY = tvTest.getTranslationY();ObjectAnimator translationY = ObjectAnimator.ofFloat(tvTest, "translationY", curTranslationY, curTranslationY + 500f);ObjectAnimator scaleY = ObjectAnimator.ofFloat(tvTest, "scaleY", 1f, 5f, 1f);ObjectAnimator scaleX = ObjectAnimator.ofFloat(tvTest, "scaleX", 1f, 5f, 1f);AnimatorSet animSet = new AnimatorSet();animSet.play(scaleY).with(scaleX).after(translationY);animSet.setDuration(2000);animSet.start();

讓界面動起來!屬性動畫淺談!

動畫混合

這裡就是將垂直移動動畫, 水平縮放和垂直縮放混合在一起, 大家肯定發現了, play(), with(), after()這幾個函數.

  • after(Animator anim) after中的動畫先執行, 之後才是play中的動畫.

  • after(long delay) after中設置時間, 那麼play中的動畫會根據時間延遲執行.

  • before(Animator anim) before中的動畫後執行, play中的先執行.

  • with(Animator anim) play中的動畫和with中的一同執行.

  • playTogether() 中間可以放入要一起執行的全部動畫, 之後不可接after(), before()這些函數. 來個小栗子.

AnimatorSet animSet = new AnimatorSet();animSet.playTogether(translationY, scaleX, scaleY);animSet.setDuration(2000);animSet.start();

讓界面動起來!屬性動畫淺談!

動畫混合


將動畫寫在xml中

寫在xml中的好處不言而喻了, 複用性極強. 直接貼代碼了, 很好理解的.

        

然後使用如下代碼調用xml動畫.

AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(getApplicationContext(), R.animator.anim_set);set.setTarget(tvTest);set.start();

動畫監聽

動畫監聽是很有必要知道的, 我們是在做軟件, 不是在做電影, 不能讓它一個勁播下去. 先看一個比較全面的監聽.

translationY.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { }});

這個很麻煩啦, 所以有適配版本的監聽. 如果你用Android Studio它會彈出框讓你選擇.

讓界面動起來!屬性動畫淺談!

監聽選擇

translationY.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); }});

最後


分享到:


相關文章: