[英]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>
最简单的方法是旋转整个按钮(正如 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;
您可以在按钮中将位图设置为背景。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.