web-dev-qa-db-fra.com

Arrêtez AnimatorSet of ObjectAnimators dans Android

Im essayant d'arrêter l'animation d'un ImageView lorsqu'un bouton est cliqué. L'animation que j'utilise est un AnimatorSet composé de 5 ObjectAnimators... Le problème est que je n'arrive pas à comprendre comment arrêter et effacer cette animation du ImageView lorsque le bouton est cliqué comme btn.clearAnimation() ne fonctionne évidemment pas.

Merci de votre aide.

19
MajorDanger

Vous devriez pouvoir appeler animatorSet.cancel() pour annuler l'animation. Voici un exemple qui annule l'animation 5 secondes après son démarrage:

package com.example.myapp2;

import Android.animation.Animator;
import Android.animation.AnimatorSet;
import Android.animation.ObjectAnimator;
import Android.app.Activity;
import Android.os.Bundle;
import Android.os.Handler;
import Android.widget.TextView;

import Java.util.ArrayList;
import Java.util.List;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.hello_world);

        List<Animator> animations = new ArrayList<Animator>();

        animations.add(ObjectAnimator.ofInt(tv, "left", 100, 1000).setDuration(10000));
        animations.add(ObjectAnimator.ofFloat(tv, "textSize", 10, 50).setDuration(10000));

        final AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(animations);
        animatorSet.start();

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                animatorSet.cancel();
            }
        }, 5000);
    }
}
13
Jessie A. Morris

Si vous aviez AnimatorSet écouteurs ajoutés, assurez-vous de supprimer les écouteurs avant d'annuler.

animatorSet.removeAllListeners();
animatorSet.end();
animatorSet.cancel();
32
Libin