最终,您希望通过动画将视图从一个位置移动到另一个位置。
第 1 步:获取该视图的初始位置
int fromLoc[] = new int[2];
v.getLocationOnScreen(fromLoc);
float startX = fromLoc[0];
float startY = fromLoc[1];
第二步:获取目标位置
int toLoc[] = new int[2];
desti.getLocationOnScreen(toLoc);
float destX = toLoc[0];
float destY = toLoc[1];
第三步:创建一个类来管理动画
public class Animations {
public Animation fromAtoB(float fromX, float fromY, float toX, float toY, AnimationListener l, int speed){
Animation fromAtoB = new TranslateAnimation(
Animation.ABSOLUTE, //from xType
fromX,
Animation.ABSOLUTE, //to xType
toX,
Animation.ABSOLUTE, //from yType
fromY,
Animation.ABSOLUTE, //to yType
toY
);
fromAtoB.setDuration(speed);
fromAtoB.setInterpolator(new AnticipateOvershootInterpolator(1.0f));
if(l != null)
fromAtoB.setAnimationListener(l);
return fromAtoB;
}
}
第 4 步:添加动画侦听器并在所需视图上启动动画
AnimationListener animL = new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//this is just a method call you can create to delete the animated view or hide it until you need it again.
clearAnimation();
}
};
//现在开始动画,如下所述:
Animations anim = new Animations();
Animation a = anim.fromAtoB(startX, startY, destX, destY, animL,850);
v.setAnimation(a);
a.startNow();
我希望它会有所帮助!