Android:无法使 StateList 可绘制对象工作

Android: Cannot get a StateList drawable to work

我正在尝试使状态列表可绘制以用作图像按钮的背景。

我正在使用这些 PNG 文件

我的状态列表选择器是这样的:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/play_button_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/play_button_pressed" android:state_focused="true" />
    <item android:drawable="@drawable/play_button_normal" />
</selector>

图片按钮是这样的:

<ImageButton
            android:id="@+id/play_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/play_button_bg"
            />

但是按钮显示为具有大图像和背景,点击它时没有任何反应。这里有什么问题吗?

代码没有问题。由于两张图片完全相同,因此当我们点击图片按钮时看起来没有任何变化。将一张图片更改为其他 png,比如暂停按钮图片并尝试。还使用 ImageView 代替 ImageButton。

改为:

<ImageButton
        android:id="@+id/play_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:scaleType="center"
        android:src="@drawable/play_button_bg"
        android:background="@null"/>

背景默认拉伸以适合视图。所以两个按钮都被改了,最后看起来是一模一样的。

用作源并将它们缩放为 "center without scaling",应该会显示两个按钮的变化(尽管最终效果可能与您预期的不完全一样)。

作为一般规则,如果所有可绘制对象都具有相同的大小,状态可绘制对象会减少麻烦。

好的,我设法使用带有图层列表的状态列表选择器解决了这个问题:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <layer-list>
            <item>
                <bitmap android:src="@drawable/play_button_pressed" android:gravity="center" />
            </item>
        </layer-list>
    </item>
    <item android:state_focused="true">
        <layer-list>
            <item>
                <bitmap android:src="@drawable/play_button_pressed" android:gravity="center" />
            </item>
        </layer-list>
    </item>
    <item android:drawable="@drawable/play_button_normal" />
</selector>

诀窍在于位图: android:重力="center"