使用android:rotation的XML旋转按钮

3

我想要一个按钮(作为图像)只在界面上顺时针旋转。我不想要在点击按钮时旋转。只在 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" />
3个回答

5
<?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值


谢谢,这很有帮助。由于我的声望较低,我无法投票支持。 - SibhiRajan
@SibhiRajan 很高兴知道它对你有帮助。 - PPD
大家好,@PPD 你能告诉我这段代码应该放在哪里吗? - fredmaggiowski
1
@FredMaggiowski 把它放在 res/anim 文件夹下。 - PPD

1

创建一个名为rotation.xml的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) );

希望能有所帮助!

我想要实时查看设计。因此,在运行时添加动画是无法帮助的。 - SibhiRajan
它会做你想要的。 - Tushar Gogna

1
您可以在按钮的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;
            }
        });

OP问如何使用XML旋转一个视图。你的方法没有使用XML。因此,这篇帖子并没有回答问题。 - Bö macht Blau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接