Android移動動畫問題

來源:互聯網
上載者:User

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) 前執行,否則會出錯~至此大功告成~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.