當我們應用android平移動畫時,一般會給動畫一個監聽,當動畫結束時,會將view的位置重新繪製到我們想要的位置,因爲平移動畫並沒與真的改變控件的實際位置.
代碼如下:
Animation animation = new TranslateAnimation(0, 0, 0, -mTop);
animation.setDuration(ANI_TIME);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//動畫結束後更新view到終點位置
mTopView.layout(left, top, right, bottom);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mTopView.startAnimation(animation);
但是實際使用的時候,當更新實際位置的時候,view會有跳動,在stackoverflow中有人貼出瞭解決方案
代碼如下:
Animation animation = new TranslateAnimation(0, 0, 0, -mTop);
animation.setDuration(ANI_TIME);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//防止跳動
TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f);
animation.setDuration(1);
mTopView.startAnimation(animation);
//動畫結束後更新view到終點位置
mTopView.layout(left, top, right, bottom);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mTopView.startAnimation(animation);
在實際寫的時候,偶然發現另一種方式也是有效的,不過這種有點違反直覺,就是倒着寫動畫,先把view更新到終點位置,代碼如下:
//由於更新到終點位置,座標參考以終點爲參考系
Animation animation = new TranslateAnimation(0, 0, mTop, 0);
animation.setDuration(ANI_TIME);
mTopView.startAnimation(animation);
//更新到終點位置
mTopView.layout(left, top, right, bottom);
但是,爲何出現view跳動的原因一直沒找到分析的文章,若有人知道望請告知.