Как воспроизвести последовательно список AnimatorSet?
Я пытаюсь сделать анимацию изображения, которое вращается вокруг формы круга. Вот текущий код, который работает, но без повторения анимации с другими значениями:
public void runAnimation(){
ImageView worldView=findViewById(R.id.imageView);
int radius=worldView.getHeight()*30/70;
int centerx = worldView.getLeft()+radius;
int centery = worldView.getTop()+radius;
//List<Animator> myList = new ArrayList<>();
for (int i=0;i<360;i++) {
/*---I calculate the points of the circle---*/
int angle= (int) ((i * 2 * Math.PI) / 360);
int x= (int) (centerx+(radius*Math.cos(angle)));
int y= (int) (centery+(radius*Math.sin(angle)));
/*---Here carView is the ImageView that need to turn around the worldView---*/
ObjectAnimator animatorX =ObjectAnimator.ofFloat(carView, "x",x);
ObjectAnimator animatorY =ObjectAnimator.ofFloat(carView, "y",y);
ObjectAnimator animatorR =ObjectAnimator.ofFloat(carView, "rotation", i);
animatorX.setDuration(500);
animatorY.setDuration(500);
animatorR.setDuration(500);
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.playTogether(animatorX,animatorY,animatorR);
animatorSet.start();
//myList.add(animatorSet);
}
//AnimatorSet animatorSet=new AnimatorSet();
//animatorSet.playSequentially(myList);
}
Комментарий ("//") здесь для иллюстрации того, что я хочу создать. Заранее благодарю за помощь.
1 ответ
Решение
Вы можете добавить слушателя к каждому AnimatorSet
используя addListener(Animator.AnimatorListener listener)
,
for (int i=0;i<360;i++) {
// ...skipped some lines here...
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.playTogether(animatorX,animatorY,animatorR);
myList.add(animatorSet);
animatorSet.addListener(myListener);
}
где myListener определяется следующим образом:
private Animator.AnimatorListener myListener = new Animator.AnimatorListener(){
@Override
public void onAnimationStart(Animator animation){
// no op
}
@Override
public void onAnimationRepeat(Animator animation){
// no op
}
@Override
public void onAnimationCancel(Animator animation){
// no op
}
@Override
public void onAnimationEnd(Animator animation){
startNextAnimation();
}
};
В дополнение к этому, вам нужна переменная private int counter;
перебирать список. Перед запуском первой анимации вы устанавливаете ее на ноль:
counter = 0;
myList.get(0).start();
Чтобы запустить следующую анимацию (если она еще есть):
private void startNextAnimation(){
counter++;
if(counter == myList.size()){
return;
}
myList.get(counter).start();
}