Android - 在按钮内旋转图像

Android - Rotate image inside the button

我想在单击按钮时旋转按钮内的图像。我尝试只使用 ImageView,它可以工作,但出于可访问性目的,我需要使用 Button 而不是 ImageView。

点击前:

这里的向下箭头是按钮背景。

点击后:

点击按钮显示额外数据,背景箭头旋转。如何在点击时设置动画和旋转按钮背景?

供参考的布局代码:

<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>

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

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);

最简单的方法是旋转整个按钮(正如 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());
    }
});

编辑:顺便说一句,如果你想让箭头反转它原来的动画,你可以试试:

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

而不是float deg = button.getRotation() + 180F;