Android - 在按钮内旋转图像

8
我想在单击按钮时旋转按钮内的图像。我尝试使用ImageView,它可以工作,但出于可访问性目的,我需要使用Button而不是ImageView。
点击前:enter image description here 这里向下箭头是按钮背景。
点击后:enter image description here 单击按钮会显示额外的数据并旋转背景箭头。如何在单击时动画和旋转按钮背景?
布局代码供参考:
<RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical" >

            <LinearLayout
                android:id="@+id/cases_actions_row"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:orientation="horizontal" >

                <Button
                    android:id="@+id/case_action_item_1"
                    style="@style/card_action_button"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content" />

                <Button
                    android:id="@+id/case_action_item_2"
                    style="@style/card_action_button"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content" />

            </LinearLayout>

            <Button
                    android:id="@+id/cases_expand_button"
                    style="@style/card_action_button"
                    android:layout_height="20dp"
                    android:layout_width="20dp"
                    android:layout_alignParentEnd="true"
                    android:layout_centerVertical="true"
                    android:background="@drawable/ic_arrow" />

        </RelativeLayout>

1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Phantômaxx
谢谢Frank。我会仔细阅读文档。我可以在更改图像时添加动画吗? - kumar
ImageButton 继承自 ImageView。但它看起来像一个 Button。所以,如果它在 ImageView 上工作(你说过的),它也会在 ImageButton 上工作。 - Phantômaxx
2个回答

22

最简单的方法是旋转整个按钮(正如Frank N. Stein在评论中建议的那样,ImageButton可能最适合,虽然您也可以使用其他小部件)。

有几种方法可以旋转按钮,但是ViewPropertyAnimator可能是最直接的方法:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        float deg = button.getRotation() + 180F;
        button.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator());
    }
});

编辑:顺便说一下,如果您想让箭头反转其原始动画,您可以尝试使用以下代码:

Edit: 顺便说一下,如果您想让箭头在反向播放其原始动画,则可以尝试以下内容:

float deg = (button.getRotation() == 180F) ? 0F : 180F;

替换为float deg = button.getRotation() + 180F;


如果整个按钮旋转,那么如果按钮有背景,背景也会随之旋转。 - Tooniis
是的,但这并不是提问者问题中的问题。 - PPartisan

2

您可以将位图设置为按钮的背景。

Matrix matrix = new Matrix();

matrix.postRotate(90);

Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true);

Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);

首先从任何源获取位图,然后旋转它,然后将其设置为按钮的背景。

BitmapDrawable bdrawable = new BitmapDrawable(context.getResources(),bitmap);
button.setBackground(bdrawable);

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