我正在创建一个应用程序,其资源可重复使用(因为按钮始终相同,但镜像或旋转)。我确实想使用相同的资源,因此我不必再添加 3 个与原始资源完全相同但已旋转的资源。但我也不想将代码与可以在 XML 中声明的内容混合在一起,或者使用会花费处理时间的矩阵进行转换。
我有一个在 XML 中声明的两状态按钮。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/and_card_details_button_down_left_onclick" /> <!-- pressed -->
<item android:drawable="@drawable/and_card_details_button_down_left" /> <!-- default -->
</selector>
我想重用drawable,因为它是相同的,但旋转了90º和45º,我将按钮分配给drawable。
<Button android:id="@+id/Details_Buttons_Top_Left_Button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/details_menu_large_button" />
我知道我可以用 RotateDrawable
旋转它或使用 Matrix
但正如我已经解释过的,我不喜欢这种方法。
是否可以直接在 XML 上实现,或者您认为最好的方法是什么?把所有资源除了轮换,在代码里轮换?
--- 编辑 --- @dmaxi 的答案效果很好,这就是如何将它与项目列表结合起来:)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<rotate
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:drawable="@drawable/and_card_details_button_up_onclick"/>
</item>
<item>
<rotate
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:drawable="@drawable/and_card_details_button_up_onclick"/>
</item>
</selector>
最佳答案
我可以 rotate在 XML 中:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:drawable="@drawable/mainmenu_background">
</rotate>
fromDegrees
很重要。
基本上这是一个用 XML 定义的旋转动画。使用 fromDegrees
您可以定义初始旋转状态。 toDegrees
是动画序列中可绘制对象的最终旋转状态,但如果您不想使用动画,则可以是任何值。
我不认为它为动画分配资源,因为它不必作为动画加载。作为一个drawable,它被渲染为它的初始状态,应该放在 drawable
资源文件夹中。
要将它用作动画,您应该将它放在 anim
资源文件夹中,并且可以像这样启动动画(只是一个示例):
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation);
rotation.setRepeatCount(Animation.INFINITE);
myView.startAnimation(rotation);
关于android - 是否可以在 xml 描述中旋转可绘制对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8716289/