Utiliser l'animation pour réaliser la rotation des composants

L'animation peut implémenter une animation simple des composants, par exemple : la rotation des composants. Les étapes de mise en œuvre sont les suivantes :

1. Créez un nouveau fichier de configuration d'animation.
app/src/main/res/anim/image_animation.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <rotate
        android:duration="5000"
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="-1"
        android:repeatMode="restart" />

</set>

Remarque :
durée : temps, en millisecondes.
fromDegrees : Rotation de quelques degrés.
toDegrees : Rotation de quelques degrés.
pivotX : le rapport du centre de rotation au sommet gauche du composant, 50 % signifie que le centre de rotation se trouve au milieu de la ligne horizontale.
pivotY : le rapport du centre de rotation au sommet supérieur du composant, 50 % signifie que le centre de rotation se trouve au milieu de la ligne verticale.
repeatCount : Le nombre de fois pour répéter la rotation, -1 signifie répéter la rotation tout le temps.
repeatMode : Mode de répétition, recommencer les répétitions depuis le début.

2. Le fichier java réalise l'animation.
TestActivity.java

package com.xiboliya.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

public class TestActivity extends Activity {
    private ImageView imgCover;
    private Animation animation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_test);
        initView();
    }

    private void initView() {
        imgCover = findViewById(R.id.img_cover);
        imgCover.setTag("0");
        imgCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击图片开始旋转或停止旋转
                updateCover();
            }
        });
    }

    private Animation getAnimation() {
        if (animation == null) {
            animation = AnimationUtils.loadAnimation(this, R.anim.image_animation);
            animation.setInterpolator(new LinearInterpolator());
        }
        return animation;
    }

    private void updateCover() {
        if ("0".equals(imgCover.getTag())) {
            // 开始旋转
            imgCover.startAnimation(getAnimation());
            imgCover.setTag("1");
        } else {
            // 停止旋转
            imgCover.clearAnimation();
            imgCover.setTag("0");
        }
    }

}

Guess you like

Origin blog.csdn.net/chenzhengfeng/article/details/130066878