使用 android:rotation xml 旋转按钮

rotate a button with android:rotation xml

我想要一个按钮(作为图像)顺时针旋转 UI。我不想旋转按钮 onClick。只需在 xml 文件中旋转就足够了。 android:rotation 对我不起作用。

我的密码是

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Button" android:background="@drawable/button" android:rotation="-90" android:id="@+id/button" android:layout_gravity="right|left" android:layout_centerVertical="true" android:layout_centerHorizontal="true" />

创建一个 XML 文件假设 rotation.xml 并将其放入名为 anim(在 res 中)的文件夹中

打开该文件并写入以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotY="50%"
    android:repeatCount="infinite" //you can change it according to the duration you want it ti rotate
    android:duration="1200" />

然后在您的代码中在 OnCreate 中执行此操作:

button.startAnimation( 
    AnimationUtils.loadAnimation(activity, R.anim.rotation) );

希望对您有所帮助!

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="600"
    android:repeatMode="restart"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/cycle_interpolator"/>

</set>

顺时针——使用正 toDegrees 值

逆时针方向——使用负 toDegrees 值

您可以在按钮 OnClick 中使用以下代码简单地旋转按钮: ObjectAnimator.ofFloat(v, "rotation", 0, 360).start();
这里,'v' 是按钮视图。这是一个例子:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ObjectAnimator.ofFloat(v, "rotation", 0f, 360f).start();     
                return false;
            }
        });