android - 是否可以在 xml 描述中旋转可绘制对象?

我正在创建一个应用程序,其资源可重复使用(因为按钮始终相同,但镜像或旋转)。我确实想使用相同的资源,因此我不必再添加 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);

https://stackoverflow.com/questions/8716289/

相关文章:

android - 如何在 Activity 启动时在 ScrollView 中滚动到底部

android - 如何以编程方式在 View 中设置样式属性

android - 使用按钮背景颜色为我的按钮添加波纹效果?

android - 在 Android 中删除 SQLite 中的行

android - 为什么一个 Android Studio 项目中有两个 build.gradle

android - 如何检测Android中布局的方向变化?

android - 同步 ScrollView 滚动位置 - android

android - 如何检查 Activity 是在前台还是在可见背景中?

android - 如何使用 HTML 5 创建一个安卓应用程序

android - Html 列表标签在 android textview 中不起作用。我能做些什么