我正在创建一个应用程序,其资源可以重复使用(因为按钮总是相同,但是镜像或旋转) . 我确实想要使用相同的资源,所以我不必再添加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>
3 回答
我可以在XML中向右旋转左箭头:
附图供参考 .
我可以rotate用XML:
fromDegrees
很重要 .基本上这是一个用XML定义的旋转动画 . 使用
fromDegrees
定义初始旋转状态 .toDegrees
是动画序列中drawable的最终旋转状态,但如果您不想使用动画,则可以是任何内容 .我不必将't think it allocates resources for animation as it doesn'加载为动画 . 作为drawable,它呈现为初始状态,应该放在
drawable
资源文件夹中 . 要将它作为动画使用,你应该把它放在anim
资源文件夹中,并且可以像这样开始动画(只是一个例子):如果使用基于矢量的drawable,结合 ImageView ,样式和颜色状态列表,您的按钮可以重构如下:
Note: 矢量drawables明显小于图像,所以额外的,明确的定义不应该避免手动修改矢量资产,我宁愿处理更新几个文件的开销,而不是在一个文件上进行转换):
Note: Android Studio是矢量资产的绝佳来源 .
res\values\styles.xml
res\color\button_csl.xml
details_menu_large_button.xml
Details_Buttons_Top_Left_Button
and_card_details_button_down_left.xml (ic_play_arrow_black_24dp.xml)
and_card_details_button_down_left_onclick.xml (修改了ic_play_arrow_black_24dp.xml)