Android 一组连续旋转动画如何实现
时间: 2024-01-30 16:02:31 浏览: 19
Android 中可以通过使用 `RotateAnimation` 类来实现一组连续的旋转动画。以下是一个简单的示例,该示例将两个旋转动画应用于一个按钮,使其不断地顺时针和逆时针旋转。
1. 在 XML 文件中定义按钮和动画:
```xml
<Button
android:id="@+id/button_rotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate" />
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1000"
android:repeatCount="infinite"
android:interpolator="@android:anim/linear_interpolator"
android:repeatMode="restart"
android:id="@+id/rotate_clockwise"/>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="-360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1000"
android:repeatCount="infinite"
android:interpolator="@android:anim/linear_interpolator"
android:repeatMode="restart"
android:id="@+id/rotate_anticlockwise"/>
```
2. 在 Java 代码中获取按钮和动画对象,并应用动画:
```java
Button buttonRotate = findViewById(R.id.button_rotate);
RotateAnimation rotateClockwise = (RotateAnimation) AnimationUtils.loadAnimation(this, R.anim.rotate_clockwise);
RotateAnimation rotateAntiClockwise = (RotateAnimation) AnimationUtils.loadAnimation(this, R.anim.rotate_anticlockwise);
buttonRotate.startAnimation(rotateClockwise);
buttonRotate.startAnimation(rotateAntiClockwise);
```
在此示例中,我们获取了按钮对象和两个旋转动画对象,并将这两个动画应用于按钮。`startAnimation()` 方法将启动动画并将其应用于指定的视图对象。在此示例中,按钮将不断地顺时针和逆时针旋转。
注意,为了使动画无限循环,我们设置了 `repeatCount` 属性为 `infinite`,并将 `repeatMode` 属性设置为 `restart`。