问题很简单,但我试图在其他类似的问题中搜索解决方案,我无法做到。 我有一个arraylist 路径包含 Coordinata 类型的对象,它是一个包含两个浮点X和Y的对象,即一个坐标。实质上,它是一个坐标列表。我需要我的ImageView 图像在我的视图上的地图上移动,在列表路径中包含的坐标之间执行几个后续的TranslateTrasformation。
这可以很容易地在翻译数量固定的情况下完成,进行第一次翻译并附加一个 setAnimationListener ,它可以捕捉第一个动画的结尾并在那个时刻开始第二个动画等等。我尝试使用while循环在我的列表路径上迭代该过程,因为我无法真正知道动画开始时路径中将有多少坐标。 结果是动画继续前几个坐标,然后跳转执行路径中最后两个坐标的动画,忽略其中的所有坐标。
发生了什么事?我弄乱了对象?
List<Coordinata> path; // properly filled with coordinates
Coordinata coordTempStart;
Coordinata coordTempArrival;
ImageView image;
ListIterator<Coordinata> pathIterator = path.listIterator();
if(pathIterator.hasNext()){
coordTempStart = (Coordinata) pathIterator.next();
}
if(pathIterator.hasNext()){
coordTempArrival = (Coordinata) pathIterator.next();
animation = new TranslateAnimation(coordTempStart.getX(),
coordTempArrival.getX(),
coordTempStart.getY(),
coordTempArrival.getY());
animation.setDuration(3000);
image.startAnimation(animation);
}
while(pathIterator.hasNext()){
coordTempStart=coordTempArrival;
coordTempArrival = (Coordinata) pathIterator.next();
animation.setAnimationListener(new TranslateAnimation.AnimationListener(){
public void onAnimationStart(Animation arg0) {}
public void onAnimationRepeat(Animation arg0) {}
public void onAnimationEnd(Animation arg0) {
animation = new TranslateAnimation(coordTempStart.getX(),
coordTempArrival.getX(),
coordTempStart.getY(),
coordTempArrival.getY());
animation.setDuration(3000);
image.startAnimation(animation);
}
});
}
答案 0 :(得分:2)
我建议使用ObjectAnimator和AnimatorSet为视图制作动画。对象动画师仅适用于api> 11但是如果你必须保持兼容性,你可以使用NineOldAndroid。
您的代码将是这样的(伪代码):
...
AnimatorSet animatorSet = new AnimatorSet();
while(pathIterator.hasNext()){
...
//Set _your_delta_x_ and _your_delta_y_ from iterator
...
ObjectAnimator xTrasnlationObjectAnimator = ObjectAnimator.ofFloat(v, view_x, _your_delta_x_);
ObjectAnimator yTrasnlationObjectAnimator = ObjectAnimator.ofFloat(v, view_y, _your_delta_y_);
animatorSet.playSequentially(xTrasnlationObjectAnimator, yTrasnlationObjectAnimator);
}
...
animatorSet.start()
设置对象动画师的正确参数请参阅官方文档http://developer.android.com/reference/android/animation/ObjectAnimator.html
答案 1 :(得分:1)
为了完整起见,我发布了用于解决问题的实际代码:
// in this list you can insert as many animations you want
List<Animator> animations = new ArrayList<Animator>();
AnimatorSet animatorSet = new AnimatorSet();
ObjectAnimator xTrasnlationObjectAnimator = ObjectAnimator.ofFloat(image, View.TRANSLATION_X, (float)300);
xTrasnlationObjectAnimator.setRepeatCount(0);
ObjectAnimator yTrasnlationObjectAnimator = ObjectAnimator.ofFloat(image, View.TRANSLATION_Y, (float)300);
yTrasnlationObjectAnimator.setRepeatCount(0);
ObjectAnimator x2TrasnlationObjectAnimator = ObjectAnimator.ofFloat(image, View.TRANSLATION_X, (float)400);
x2TrasnlationObjectAnimator.setRepeatCount(0);
animations.add(xTrasnlationObjectAnimator);
animations.add(yTrasnlationObjectAnimator);
animations.add(x2TrasnlationObjectAnimator);
animatorSet.playSequentially(animations);
animatorSet.start();