Introduction à cette section :
Cette section présente le troisième type d'animation sous Android - l'animation de propriété. Rappelez-vous dans la section précédente8.4.2 Collection d'animations Android : Animation par interpolationLors de la définition d'animations de transition pour Fragment, nous avons mentionné que les types d'animation correspondant à l'appel setCustomAnimations() pour les Fragments sous le package App et le package V4 sont différents. Le package v4 utiliseAnimation, tandis que le package app utiliseAnimator;
Animation (animation générale)ce que nous avons appris précédemmentanimation d'images et animation par interpolation!Animatortandis que cette section couvrel'animation de propriété!
Concernant l'animation de propriété, l'expert Oncle Guo a déjà écrit trois excellents articles récapitulatifs. Ils sont très bien écrits, donc pas besoin de réinventer la roue. Cependant, je vais quand même le parcourir ici. La plupart du contenu fait référence aux trois articles suivants :
Ils sont très bien écrits, ou vous pouvez ignorer directement cet article et lire les trois articles ci-dessus~
Bien sûr, si vous êtes prêt à m'écouter divaguer, vous êtes également le bienvenu. Très bien, commençons le contenu de cette section~
1. Digression sur le concept d'animation de propriété
Fini le bavardage, passons directement au schéma, comme ça~

2. Utilisation simple de ValueAnimator
Flux d'utilisation:
- 1. Appelez la méthode statique de ValueAnimatorofInt(),ofFloat() ouofObject() pour créer une instance de ValueAnimator
- 2. Appelez les méthodes setXxx de l'instance pour définir la durée de l'animation, la méthode d'interpolation, le nombre de répétitions, etc.
- 3. Appelez la méthodeaddUpdateListeneraddAnimatorUpdateListenerlistener de l'instance. Dans ce listener, vous pouvez obtenir la valeur calculée par ValueAnimator, et vous pouvez appliquer la valeur à l'objet spécifié~
- 4. Appelez la méthodestart()de l'instance pour démarrer l'animation ! De plus, on peut voir que ofInt et ofFloat ont tous les deux un paramètre comme ceci : float/int... values, ce qui signifie que plusieurs valeurs sont autorisées !
Exemple d'utilisation:

Implémentation du code:
Fichier de mise en page :activity_main.xml, très simple, quatre boutons et un ImageView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ly_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="动画1" />
<Button
android:id="@+id/btn_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="动画2" />
<Button
android:id="@+id/btn_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="动画3" />
<Button
android:id="@+id/btn_four"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="动画4" />
<ImageView
android:id="@+id/img_babi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@mipmap/img_babi" />
</LinearLayout>
Ensuite, allez dansMainActivity.java, nous avons d'abord besoin d'une méthode pour modifier la position de la View. Ici, nous appelonsmoveView() pour définir les coordonnées de départ de left et top, ainsi que width et height !
Ensuite, quatre animations sont définies : mouvement linéaire, mise à l'échelle, rotation avec transparence et rotation circulaire !
Ensuite, déclenchez l'animation correspondante via les boutons~
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_one;
private Button btn_two;
private Button btn_three;
private Button btn_four;
private LinearLayout ly_root;
private ImageView img_babi;
private int width;
private int height;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
}
private void bindViews() {
ly_root = (LinearLayout) findViewById(R.id.ly_root);
btn_one = (Button) findViewById(R.id.btn_one);
btn_two = (Button) findViewById(R.id.btn_two);
btn_three = (Button) findViewById(R.id.btn_three);
btn_four = (Button) findViewById(R.id.btn_four);
img_babi = (ImageView) findViewById(R.id.img_babi);
btn_one.setOnClickListener(this);
btn_two.setOnClickListener(this);
btn_three.setOnClickListener(this);
btn_four.setOnClickListener(this);
img_babi.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_one:
lineAnimator();
break;
case R.id.btn_two:
scaleAnimator();
break;
case R.id.btn_three:
raAnimator();
break;
case R.id.btn_four:
circleAnimator();
break;
case R.id.img_babi:
Toast.makeText(MainActivity.this, "不愧是coder-pig~", Toast.LENGTH_SHORT).show();
break;
}
}
//定义一个修改ImageView位置的方法
private void moveView(View view, int rawX, int rawY) {
int left = rawX - img_babi.getWidth() / 2;
int top = rawY - img_babi.getHeight();
int width = left + view.getWidth();
int height = top + view.getHeight();
view.layout(left, top, width, height);
}
//定义属性动画的方法:
//按轨迹方程来运动
private void lineAnimator() {
width = ly_root.getWidth();
height = ly_root.getHeight();
ValueAnimator xValue = ValueAnimator.ofInt(height,0,height / 4,height / 2,height / 4 * 3 ,height);
xValue.setDuration(3000L);
xValue.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// 轨迹方程 x = width / 2
int y = (Integer) animation.getAnimatedValue();
int x = width / 2;
moveView(img_babi, x, y);
}
});
xValue.setInterpolator(new LinearInterpolator());
xValue.start();
}
//缩放效果
private void scaleAnimator(){
//这里故意用两个是想让大家体会下组合动画怎么用而已~
final float scale = 0.5f;
AnimatorSet scaleSet = new AnimatorSet();
ValueAnimator valueAnimatorSmall = ValueAnimator.ofFloat(1.0f, scale);
valueAnimatorSmall.setDuration(500);
ValueAnimator valueAnimatorLarge = ValueAnimator.ofFloat(scale, 1.0f);
valueAnimatorLarge.setDuration(500);
valueAnimatorSmall.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float scale = (Float) animation.getAnimatedValue();
img_babi.setScaleX(scale);
img_babi.setScaleY(scale);
}
});
valueAnimatorLarge.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float scale = (Float) animation.getAnimatedValue();
img_babi.setScaleX(scale);
img_babi.setScaleY(scale);
}
});
scaleSet.play(valueAnimatorLarge).after(valueAnimatorSmall);
scaleSet.start();
//其实可以一个就搞定的
// ValueAnimator vValue = ValueAnimator.ofFloat(1.0f, 0.6f, 1.2f, 1.0f, 0.6f, 1.2f, 1.0f);
// vValue.setDuration(1000L);
// vValue.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
// @Override
// public void onAnimationUpdate(ValueAnimator animation) {
// float scale = (Float) animation.getAnimatedValue();
// img_babi.setScaleX(scale);
// img_babi.setScaleY(scale);
// }
// });
// vValue.setInterpolator(new LinearInterpolator());
// vValue.start();
}
//旋转的同时透明度变化
private void raAnimator(){
ValueAnimator rValue = ValueAnimator.ofInt(0, 360);
rValue.setDuration(1000L);
rValue.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int rotateValue = (Integer) animation.getAnimatedValue();
img_babi.setRotation(rotateValue);
float fractionValue = animation.getAnimatedFraction();
img_babi.setAlpha(fractionValue);
}
});
rValue.setInterpolator(new DecelerateInterpolator());
rValue.start();
}
//圆形旋转
protected void circleAnimator() {
width = ly_root.getWidth();
height = ly_root.getHeight();
final int R = width / 4;
ValueAnimator tValue = ValueAnimator.ofFloat(0,
(float) (2.0f * Math.PI));
tValue.setDuration(1000);
tValue.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// 圆的参数方程 x = R * sin(t) y = R * cos(t)
float t = (Float) animation.getAnimatedValue();
int x = (int) (R * Math.sin(t) + width / 2);
int y = (int) (R * Math.cos(t) + height / 2);
moveView(img_babi, x, y);
}
});
tValue.setInterpolator(new DecelerateInterpolator());
tValue.start();
}
}
D'accord, le flux d'utilisation est très simple. Commencez par créer un objet ValueAnimator en appelant ValueAnimator.ofInt/ofFloat, puis définissez la durée de l'animation,addUpdateListenerajoutezAnimatorUpdateListenerécouteur d'événement, puis utilisez le paramètreanimationdegetAnimatedValue() pour obtenir la valeur actuelle, puis nous pouvons utiliser cette valeur pour modifier certaines propriétés de la View, formant ainsi ce qu'on appelle un effet d'animation. Ensuite, définissez le mode de rendu d'animation setInterpolator, et enfin appelez start() pour lancer la lecture de l'animation~
Mince, des équations linéaires, des équations paramétriques d'un cercle, je commence déjà à paniquer. Ce n'est pas de la mathématique avancée ? Ce cancre en sciences a même oublié les fonctions trigonométriques...
L'exemple est référencé depuis GitHub :MoveViewValueAnimator
3. Utilisation simple d'ObjectAnimator
Par rapport à ValueAnimator, ObjectAnimator semble plus facile à utiliser. Avec cette classe, nous pouvonsdirectement
effectuer des opérations d'animation sur n'importe quelle propriété de n'importe quel objet! C'est vrai, n'importe quel objet, pas seulement les objets View. Attribuez continuellement des valeurs à une certaine propriété de l'objet, puis décidez comment l'afficher en fonction des changements de la valeur de la propriété de l'objet ! Par exemple, définir l'animation suivante pour TextView :ObjectAnimator.ofFloat(textview, "alpha", 1f, 0f);
Ici, il change continuellement la valeur alpha de 1f à 0f, puis l'objet actualise l'affichage de l'interface en fonction des changements de la valeur de la propriété, produisant ainsi un effet de fondu d'apparition et de disparition. Cependant, il n'y a pas de propriété alpha dans la classe TextView. Le mécanisme interne d'ObjectAnimator est :Il cherche les méthodes get et set correspondant au nom de propriété passé, plutôt que de chercher cette valeur de propriété !Si vous ne me croyez pas, vous pouvez regarder dans le code source de TextView pour voir s'il y a une propriété alpha ! Bon, utilisons ObjectAnimator pour implémenter les effets de quatre animations tween~
Diagramme de l'effet d'exécution:

Implémentation du code:
La mise en page utilise directement la mise en page ci-dessus, ajoute un bouton et remplace l'ImageView par un TextView. Je ne vais pas coller le code ici, passons directement à la partieMainActivity.javadu code, en fait tout est à peu près identique~
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_one;
private Button btn_two;
private Button btn_three;
private Button btn_four;
private Button btn_five;
private LinearLayout ly_root;
private TextView tv_pig;
private int height;
private ObjectAnimator animator1;
private ObjectAnimator animator2;
private ObjectAnimator animator3;
private ObjectAnimator animator4;
private AnimatorSet animSet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
initAnimator();
}
private void bindViews() {
ly_root = (LinearLayout) findViewById(R.id.ly_root);
btn_one = (Button) findViewById(R.id.btn_one);
btn_two = (Button) findViewById(R.id.btn_two);
btn_three = (Button) findViewById(R.id.btn_three);
btn_four = (Button) findViewById(R.id.btn_four);
btn_five = (Button) findViewById(R.id.btn_five);
tv_pig = (TextView) findViewById(R.id.tv_pig);
height = ly_root.getHeight();
btn_one.setOnClickListener(this);
btn_two.setOnClickListener(this);
btn_three.setOnClickListener(this);
btn_four.setOnClickListener(this);
btn_five.setOnClickListener(this);
tv_pig.setOnClickListener(this);
}
//初始化动画
private void initAnimator() {
animator1 = ObjectAnimator.ofFloat(tv_pig, "alpha", 1f, 0f, 1f, 0f, 1f);
animator2 = ObjectAnimator.ofFloat(tv_pig, "rotation", 0f, 360f, 0f);
animator3 = ObjectAnimator.ofFloat(tv_pig, "scaleX", 2f, 4f, 1f, 0.5f, 1f);
animator4 = ObjectAnimator.ofFloat(tv_pig, "translationY", height / 8, -100, height / 2);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_one:
animator1.setDuration(3000l);
animator1.start();
break;
case R.id.btn_two:
animator2.setDuration(3000l);
animator2.start();
break;
case R.id.btn_three:
animator3.setDuration(3000l);
animator3.start();
break;
case R.id.btn_four:
animator4.setDuration(3000l);
animator4.start();
break;
case R.id.btn_five:
//将前面的动画集合到一起~
animSet = new AnimatorSet();
animSet.play(animator4).with(animator3).with(animator2).after(animator1);
animSet.setDuration(5000l);
animSet.start();
break;
case R.id.tv_pig:
Toast.makeText(MainActivity.this, "不愧是coder-pig~", Toast.LENGTH_SHORT).show();
break;
}
}
}
L'utilisation est également très simple. Les animations combinées mentionnées ci-dessus seront abordées ci-dessous~
4. Animations combinées et AnimatorListener
À partir des deux exemples ci-dessus, nous avons expérimenté les animations combinées, en utilisantAnimatorSetcette classe !
Nous appelons la méthode play() et passons la première animation pour commencer l'exécution. À ce stade, elle nous renvoie une classe Builder :

Ensuite, nous pouvons appeler les quatre méthodes fournies par Builder pour combiner d'autres animations :
- after(Animator anim) Insère l'animation existante pour qu'elle s'exécute après l'animation transmise
- after(long delay) Exécute l'animation existante après un délai du nombre de millisecondes spécifié
- before(Animator anim) Insère l'animation existante pour qu'elle s'exécute avant l'animation transmise
- with(Animator anim) Exécute simultanément l'animation existante et l'animation transmise
Hmm, très simple. Ensuite, parlons de l'écoute des événements d'animation. Plus haut, l'écouteur de notre ValueAnimator estAnimatorUpdateListener, et lorsque l'état de la valeur change, il rappellera la méthodeonAnimationUpdate!
En plus de ce type d'événement, il y a aussi : l'écoute de l'état d'exécution de l'animation~AnimatorListener, nous pouvons appeler la méthodeaddListenerpour ajouter un écouteur, puis redéfinir les quatre méthodes de rappel suivantes :
- onAnimationStart(): L'animation démarre
- onAnimationRepeat(): L'animation se répète
- onAnimationEnd(): L'animation se termine
- onAnimationCancel(): L'animation est annulée
C'est exact, si vous utilisez vraiment AnimatorListener, vous devez redéfinir les quatre méthodes. Bien sûr, comme dans la section sur les gestes plus haut, Android nous a déjà fourni une classe adaptateur :AnimatorListenerAdapter, cette classe implémente déjà toutes les méthodes de l'interface, donc nous pouvons simplement écrire une méthode de rappel ici !
5. Écrire des animations avec XML
Écrire des animations avec XML peut prendre un peu plus de temps que du code Java, mais les réutiliser est bien plus facile ! Les balises XML correspondantes sont : <animator><objectAnimator><set> Les attributs associés sont expliqués comme suit :
- android:ordering: Spécifie l'ordre de lecture des animations : sequentially (exécuter dans l'ordre), together (exécuter simultanément)
- android:duration: La durée de l'animation
- android:propertyName="x" : Le x ici, vous vous souvenez de "alpha" plus haut ? L'objet qui charge l'animation doit définir les méthodes getx et setx. objectAnimator utilise ceci pour modifier les valeurs dans l'objet !
- android:valueFrom="1" : La valeur initiale au début de l'animation
- android:valueTo="0" : La valeur finale à la fin de l'animation
- android:valueType="floatType" : Le type de données de la valeur changeante
Des exemples d'utilisation sont les suivants:
①Une animation qui effectue une transition fluide de 0 à 100:
<animator xmlns:android="http://schemas.android.com/apk/res/android"
android:valueFrom="0"
android:valueTo="100"
android:valueType="intType"/>
②Changer la propriété alpha d'une vue de 1 à 0:
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:valueFrom="1"
android:valueTo="0"
android:valueType="floatType"
android:propertyName="alpha"/>
③Démonstration d'utilisation de l'animation set:
<set android:ordering="sequentially" >
<set>
<objectAnimator
android:duration="500"
android:propertyName="x"
android:valueTo="400"
android:valueType="intType" />
<objectAnimator
android:duration="500"
android:propertyName="y"
android:valueTo="300"
android:valueType="intType" />
</set>
<objectAnimator
android:duration="500"
android:propertyName="alpha"
android:valueTo="1f" />
</set>
Charger notre fichier d'animation:
AnimatorSet set = (AnimatorSet)AnimatorInflater.loadAnimator(mContext,
R.animator.property_animator);
animator.setTarget(view);
animator.start();
6. Télécharger le code d'exemple de cette section :
AnimatorDemo1.zip
AnimatorDemo2.zip
Résumé de cette section :
Très bien, cette section a donné à tout le monde un aperçu de l'utilisation de base de l'animation de propriété dans Android. Je ne sais pas si vous avez compris ou non. Le contenu reste relativement simple, et les exemples sont assez intéressants. Je pense que tout le monde les appréciera. Bon, c'est tout ce que j'ai à dire, merci~
Merci àGuo the Godpour les articles~
