Android移動view動畫問題


Android寫動畫效果不是一般的麻煩,網上找了好久,終於解決了動畫的問題,總結記錄以共勉。
僅以水平方向移動效果做說明,垂直方向類似。

 

完整動畫函數代碼: 

 1  public  void slideview( final  float p1,  final  float p2) {
 2     TranslateAnimation animation =  new TranslateAnimation(p1, p2, 0, 0);
 3     animation.setInterpolator( new OvershootInterpolator());
 4     animation.setDuration(durationMillis);
 5     animation.setStartOffset(delayMillis);
 6     animation.setAnimationListener( new Animation.AnimationListener() {
 7         @Override
 8          public  void onAnimationStart(Animation animation) {
 9         }
10         
11         @Override
12          public  void onAnimationRepeat(Animation animation) {
13         }
14         
15         @Override
16          public  void onAnimationEnd(Animation animation) {
17              int left = view.getLeft()+( int)(p2-p1);
18              int top = view.getTop();
19              int width = view.getWidth();
20              int height = view.getHeight();
21             view.clearAnimation();
22             view.layout(left, top, left+width, top+height);
23         }
24     });
25     view.startAnimation(animation);
26 }

 

 

調用示例: 
移動到目標位置
slideview(0, distance);
從目標位置移回原位

slideview(0, -distance); 

 

過程中遇到的問題:

 1、動畫執行完成后,view回到原位

1 TranslateAnimation animation =  new TranslateAnimation(p1, p2, 0, 0);
2 animation.setInterpolator( new OvershootInterpolator());
3 animation.setDuration(durationMillis);
4 animation.setStartOffset(delayMillis);
5 view.startAnimation(animation);

開始時動畫效果只寫了這么多,發現動畫執行完,view會回到原位。

經過查資料嘗試使用animation.setFillAfter(true); view不再返回原位,但又出現了第2個問題


2、點擊按鈕時,view在初始位置會先閃一下,再執行動畫 

 經過查資料得知,animation.setFillAfter(true); 只是將view移動到了目標位置,但是view綁定的點擊事件還在原來位置,導致點擊時會先閃一下

又查資料找到解決辦法:
不加setFillAfter, 通過設置view位置實現效果,增加如下代碼
 1 animation.setAnimationListener( new Animation.AnimationListener() {
 2     @Override
 3      public  void onAnimationStart(Animation animation) {
 4     }
 5     
 6     @Override
 7      public  void onAnimationRepeat(Animation animation) {
 8     }
 9     
10     @Override
11      public  void onAnimationEnd(Animation animation) {
12          int left = view.getLeft()+( int)(p2-p1);
13          int top = view.getTop();
14          int width = view.getWidth();
15          int height = view.getHeight();
16         view.clearAnimation();
17         view.layout(left, top, left+width, top+height);
18     }
19 });

 

在動畫執行完畢后(onAnimationEnd)設置view的位置,同時要clearAnimation()

注:clearAnimation() 必須在 layout(l,t,r,b) 前執行,否則會出錯~
至此大功告成~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM