使用Animation实现组件旋转

Animation可以实现组件的简单动画,例如:组件旋转。实现步骤如下:

1.新建动画配置文件。
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>

注:
duration:时间,单位毫秒。
fromDegrees:从几度开始旋转。
toDegrees:旋转到几度。
pivotX:旋转中心距离组件的左顶点的比例,50%表示旋转中心位于水平线正中。
pivotY:旋转中心距离组件的上顶点的比例,50%表示旋转中心位于垂直线正中。
repeatCount:旋转重复次数,-1为一直重复旋转。
repeatMode:重复模式,restart从头开始重复。

2.java文件实现动画。
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");
        }
    }

}

猜你喜欢

转载自blog.csdn.net/chenzhengfeng/article/details/130066878
今日推荐