Introduction à cette section :
À partir de cette section, explorons les animations dans Android. Après tout, ajouter quelques animations à une application rendra notre application plus cool, comme la simple ouverture et fermeture des activités. Bien sûr, les animations de contrôles personnalisés sont absolument indispensables~ Les animations dans Android se divisent en trois grandes catégories :Animation image par image (Frame)etAnimation par interpolation (Tween)ainsi que celle introduite après Android 3.0 :Animation de propriété (Property)Et ce que cette section vous apporte, c'est une utilisation de base du premier type d'animation — l'animation image par image~
1. Concept et utilisation de l'animation image par image
L'animation image par image est très facile à comprendre. Elle consiste simplement à rassembler N images statiques, puis nous contrôlons l'affichage séquentiel de ces images. En raison de la « persistance rétinienne » de l'œil humain, elle crée l'« illusion » d'une animation, tout comme le principe de projection d'un film !
Pour implémenter une animation image par image dans Android, nous utilisons généralement un Drawable expliqué précédemment :AnimationDrawableÉcrivez d'abord le Drawable, puis appelez start() et stop() dans le code pour démarrer ou arrêter la lecture de l'animation~
Bien sûr, nous pouvons aussi créer une animation image par image dans du code Java en créant un objet AnimationDrawable, puis en appelant addFrame(Drawable frame, int duration) pour ajouter des images à l'animation, puis en appelant start() et stop()~
Ci-dessous, écrivons deux exemples pour découvrir l'effet de l'animation image par image et nous familiariser avec son utilisation.
2. Exemples d'utilisation:
Exemple 1: L'exemple le plus simple:
Capture d'écran de l'effet d'exécution:

Implémentation du code:
Tout d'abord, écrivons notre fichier d'animation. C'est très simple: créez un répertoire anim sous res, puis commencez à écrire notre fichier d'animation:miao_gif.xml: Ici android:oneshot définit si l'animation ne se joue qu'une seule fois; true signifie ne jouer qu'une seule fois, false signifie une lecture en boucle!
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item
android:drawable="@mipmap/img_miao1"
android:duration="80" />
<item
android:drawable="@mipmap/img_miao2"
android:duration="80" />
<item
android:drawable="@mipmap/img_miao3"
android:duration="80" />
<!--限于篇幅,省略其他item,自己补上-->
...
</animation-list>
Maintenant que nous avons le fichier d'animation, vient ensuite notre fichier de mise en page:activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止" />
<ImageView
android:id="@+id/img_show"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:background="@anim/miao_gif" />
</LinearLayout>
Enfin, il y a notreMainActivity.java, où nous contrôlons le démarrage et la pause de l'animation:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_start;
private Button btn_stop;
private ImageView img_show;
private AnimationDrawable anim;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
anim = (AnimationDrawable) img_show.getBackground();
}
private void bindViews() {
btn_start = (Button) findViewById(R.id.btn_start);
btn_stop = (Button) findViewById(R.id.btn_stop);
img_show = (ImageView) findViewById(R.id.img_show);
btn_start.setOnClickListener(this);
btn_stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
anim.start();
break;
case R.id.btn_stop:
anim.stop();
break;
}
}
}
Bon, c'est très simple~
Exemple 2: Lecture d'une animation image par image à un emplacement spécifié
Capture d'écran de l'effet d'exécution:

Implémentation du code:
Encore une fois, d'abord notre fichier d'animation:anim_zhuan.xml:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
<item
android:drawable="@mipmap/img_zhuan1"
android:duration="80" />
<item
android:drawable="@mipmap/img_zhuan2"
android:duration="80" />
<item
android:drawable="@mipmap/img_zhuan3"
android:duration="80" />
<!--限于篇幅,省略其他item,自己补上-->
...
</animation-list>
Ensuite, écrivons un ImageView personnalisé:FrameView.java, ici nous utilisons la réflexion pour obtenir l'image en cours de lecture, puis vérifions s'il s'agit de la dernière image; si oui, masquez le contrôle!
/**
* Created by Jay on 2015/11/15 0015.
*/
public class FrameView extends ImageView {
private AnimationDrawable anim;
public FrameView(Context context) {
super(context);
}
public FrameView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FrameView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setAnim(AnimationDrawable anim){
this.anim = anim;
}
public void setLocation(int top,int left){
this.setFrame(left,top,left + 200,top + 200);
}
@Override
protected void onDraw(Canvas canvas) {
try{
//反射调用AnimationDrawable里的mCurFrame值
Field field = AnimationDrawable.class
.getDeclaredField("mCurFrame");
field.setAccessible(true);
int curFrame = field.getInt(anim);// 获取anim动画的当前帧
if (curFrame == anim.getNumberOfFrames() - 1)// 如果已经到了最后一帧
{
//让该View隐藏
setVisibility(View.INVISIBLE);
}
}catch (Exception e){e.printStackTrace();}
super.onDraw(canvas);
}
}
Enfin, il y a notreMainActivity.java, créez un FrameLayout, ajoutez des Views, gérez l'événement d'appui dans les événements tactiles, affichez le contrôle et démarrez l'animation~
public class MainActivity extends AppCompatActivity {
private FrameView fView;
private AnimationDrawable anim = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout fly = new FrameLayout(this);
setContentView(fly);
fView = new FrameView(this);
fView.setBackgroundResource(R.anim.anim_zhuan);
fView.setVisibility(View.INVISIBLE);
anim = (AnimationDrawable) fView.getBackground();
fView.setAnim(anim);
fly.addView(fView);
fly.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//设置按下时才产生动画效果
if(event.getAction() == MotionEvent.ACTION_DOWN){
anim.stop();
float x = event.getX();
float y = event.getY();
fView.setLocation((int) y - 40,(int)x-20); //View显示的位置
fView.setVisibility(View.VISIBLE);
anim.start(); //开启动画
}
return false;
}
});
}
}
Bon, c'est aussi très simple~
3. Téléchargement du code d'exemple et de l'outil d'extraction d'images GIF pour cette section
AnimationDemo1.zip
AnimationDemo2.zip
Outil d'extraction de trames GIF
Résumé de la section :
OK, cette section a présenté la plus simple des trois types d'animations Android : l'animation par images. Elle n'est pas beaucoup utilisée en développement réel, mais apprendre plus de choses nous donne plus d'idées à l'avenir~ Bon, c'est tout pour cette section, merci~
