Android移動view動畫問題--停在動畫的最后一幀(轉)


Android寫動畫效果不是一般的麻煩,網上找了好久,終於解決了動畫的問題,總結記錄以共勉。
僅以水平方向移動效果做說明,垂直方向類似。
public void slideview(final float p1, final float p2) {
    TranslateAnimation animation = new TranslateAnimation(p1, p2, 0, 0);
    animation.setInterpolator(new OvershootInterpolator());
    animation.setDuration(durationMillis);
    animation.setStartOffset(delayMillis);
    animation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }
        
        @Override
        public void onAnimationRepeat(Animation animation) {
        }
        
        @Override
        public void onAnimationEnd(Animation animation) {
            int left = view.getLeft()+(int)(p2-p1);
            int top = view.getTop();
            int width = view.getWidth();
            int height = view.getHeight();
            view.clearAnimation();
            view.layout(left, top, left+width, top+height);
        }
    });
    view.startAnimation(animation);
}
調用示例: 
移動到目標位置
slideview(0, distance);
從目標位置移回原位

slideview(0, -distance); 

 

過程中遇到的問題:

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

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

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

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

又查資料找到解決辦法:
不加setFillAfter, 通過設置view位置實現效果,增加如下代碼
 
animation.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {
    }
    
    @Override
    public void onAnimationRepeat(Animation animation) {
    }
    
    @Override
    public void onAnimationEnd(Animation animation) {
        int left = view.getLeft()+(int)(p2-p1);
        int top = view.getTop();
        int width = view.getWidth();
        int height = view.getHeight();
        view.clearAnimation();
        view.layout(left, top, left+width, top+height);
    }
});

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

 
注:clearAnimation() 必須在 layout(l,t,r,b) 前執行,否則會出錯~
 
轉 http://www.cnblogs.com/eoiioe/archive/2012/08/29/2662546.html
 


免責聲明!

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



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