android - 按钮总是以状态列表中第一个列出的样式显示,无论其状态如何

标签 android xml statelistdrawable

长期阅读 stackoverflow,第一次提出问题。我遇到的问题看起来很愚蠢,但我找不到任何解释它的信息。

我是 Android 编程的新手,正在开发一个具有自定义按钮背景的项目。我正在为看起来像这样的不同按钮使用状态列表可绘制对象:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">


<item>
    <bitmap android:src="@drawable/button_pressed_background" android:gravity="center"/>
    android:state_pressed="true"
</item>

<item>
    <bitmap android:src="@drawable/button_focused_background" android:gravity="center"/>
    android:state_focused="true"
</item>

 <item>
    <bitmap android:src="@drawable/button_standard_background" android:gravity="center"/>
    android:state_pressed="false"
    android:state_focused="false"
</item>


</selector>

在声明按钮的 xml 中,我简单地添加了行 android:background="@drawable/button_drawable"其中 button_drawable.xml 是可绘制状态列表。

看起来很简单,但在所有情况下,按钮显示的背景都列在第一个 <item> 中。状态列表部分可绘制,无论其状态如何。事实上,在上面的示例中,我可以更改第一个 <item>要包括的部分 android:state_pressed="false"相反,button_pressed_background仍然显示!就好像所有按钮状态同时为 true 和 false。

我正在使用模拟器进行开发,但在 AVD 模拟器和在 Oracle VirtualBox 上运行的 Android x86 上都看到了这种行为。知道为什么会发生这种情况吗?

最佳答案

用下面的代码定义一个选择器并尝试把它作为背景:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/background_sel"/>
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/background_sel"/>
    <item android:state_focused="true" android:drawable="@drawable/background_sel"/>
    <item android:state_focused="false" android:state_pressed="false" android:drawable="@drawable/background_normal"/>
</selector>

关于android - 按钮总是以状态列表中第一个列出的样式显示,无论其状态如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321907/

相关文章:

java - Wit Ai for Android - 应用程序崩溃

android - 带有 StateListDrawable 的 ImageView 不起作用

android - 从公共(public)资源为自定义 ViewGroup 的多个组件创建 StateListDrawables

java - 在 x 轴上使用日期时间格式时标签过多

android - 为什么 mipmap 文件夹不显示在 XML Android Studio 的建议中?

android - 在旋转时调用 onCreate()

android - 用曲线绘制形状

c# - 保存 XmlDocument 时,它会忽略 XmlDeclaration (UTF8) 中的编码并使用 UTF16

android - Android ImageButton 背景的挑战

java - 如何修改/适配 API 库中的方法?