7.1 View動畫
- View動畫的種類:
- TranslateAnimation
- ScaleAnimation
- RotateAnimation
- AlphaAnimation
- AnimationSet
- View動畫既可以在res/anim/filename.xml,也可以代碼動態創建
- 使用動畫的方法:
Button mButton = (Button)findViewById(R.id.button1);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.animation_test);
AlphaAnimation alphaAnimation = new AlphaAnimtaion(0,1);
alphaAnimtaion.setDruation(300);
mButton.startAnimation(animtaion);
mButton1.startAnimtaion(alphaAnimation);
- 可以通過setAnimationListener來添加動畫的監聽
- 自定義View動畫
- initialize:初始化工作
- applyTransformation:相應的矩陣變換
- 幀動畫 : AnimationDrawable
一般使用一個xml來定義,使用時
AnimationDrawable drawable = (AnimationDrawable)mButton.getBackground();
drawable.start();
7.2 View動畫的特殊使用場景
- LayoutAnimtaion
- LayoutAnimtaion給ViewGroup的子元素加上出場效果
- 可以在xml中制定android:layoutAnimation,也可以使用LayoutAnimtaionController來實現
- Activity的切換效果, 當startActvity和finish時
overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
- Fragment的切換也可以使用View動畫
7.3 屬性動畫
- 屬性動畫可以對任何對象做動畫,而不僅僅是View,甚至可以沒有對象。常用的屬性動畫有ValueAnimator,ObjectAnimator,AnimatorSet
//ObjectAnimator
ObjectAnimator.ofFloat(myObject, "translationY", - myObject.getHeight()).start();
//ValueAnimator
ValueAnimator colorAnim = ObjectAnimator.ofInt(this, "backgroundColor",0xFFFF8080,0xFF8080FF);
colorAnim.setDuration(3000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE); //動畫重復次數
colorAnim.setRepeatMode(ValueAnimator.REVERSE); //動畫的重復模式
colorAnim.start();
//AnimatorSet
AnimatorSet set = new AnimatorSet();
set.playTogether(
ObjectAnimator.ofFloat(myView, "rotationX", 0, 360);
ObjectAnimator.ofFloat(myView, "rotaitonY", 0, 180);
......
);
set.setDuration(5*1000).start();
- 屬性動畫可以用代碼實現,也可以用xml實現,建議使用代碼實現。
- 插值器TimeInterpolator:根據時間流逝的百分比計算出當前屬性值改變的百分比
- 估值器 TypeEvalutor:根據屬性百分比的變化計算當前屬性的值
- 屬性動畫的監聽器
- AnimatorListener:監聽動畫的開始、結束、取消、重復播放
- AnimatorUpdateListener:監聽整個過程,每播放一幀,onAnimationUpdate就會調用一次
- 屬性動畫的要求
- object必須提供getAbc和setAbc方法
- object的setAbc對屬性abc的改變必須能通過某些方法反映出來,比如帶來UI的改變。
- TextView和Button的setWidth/getWidth干的不是一件事情
- 保證屬性動畫生效的三種解決方法:
- 給對象加上get/set方法,如果有權限的話(不現實)
- 用一個類包裝對象,間接提供get/set方法——最現實
- 采用ValueAnimator,監聽動畫過程,自己實現屬性改變
- ValueAnimator本身不作用于任何對象,直接使用他不會有任何動畫效果。
7.4 使用動畫的注意事項:
- 避免使用幀動畫,易OOM
- 無限循環的動畫,要在Activity退出時及時停止,否則會出現內存泄漏
- View動畫只改變內容
- 盡量使用dp
- 建議開啟硬件加速
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。