2025-04-23

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) 前執行,否則會出錯~

至此大功告成~

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *