我为我的按钮背景制作了一个自定义的 9 补丁图像。按钮位于 drawable-hdpi 和 drawable-mdpi 文件夹中。我为我的按钮状态创建了自定义选择器文件。
选择器文件 login_button.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Image display in background in select state -->
<item android:state_pressed="true" android:drawable="@drawable/login_button_down" />
<!-- Image display in background in select state -->
<item android:state_focused="true" android:drawable="@drawable/login_button_down" />
<!-- Default state -->
<item android:drawable="@drawable/login_button" />
</selector>
然后我为按钮样式制作了一个自定义的 styles.xml 文件:
<style name="login_button_style" parent="@android:style/Widget.Button">
<item name="android:gravity">center_vertical|center_horizontal</item>
<item name="android:textColor">#FF000000</item>
<item name="android:shadowColor">#FFFFFFFF</item>
<item name="android:shadowDx">0</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">0.2</item>
<item name="android:textSize">13dp</item>
<item name="android:textStyle">bold</item>
<item name="android:background">@drawable/login_button</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
</style>
然后在themes.xml中将这个样式应用到我的主题文件中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="customTheme" parent="@android:style/Theme.NoTitleBar" >
<item name="android:editTextStyle">@style/login_edittext_style</item>
<item name="android:buttonStyle">@style/login_button_style</item>
<item name="android:textViewStyle">@style/login_textview_style</item>
</style>
</resources>
最后将按钮本身添加到布局文件中:
<Button
android:text="@string/login_text"
android:id="@+id/buttonSignIn"
android:layout_width="130dp"
android:layout_height="wrap_content">
</Button>
但是如果我点击按钮,背景图像不会改变。代码没问题,所有编译都很好。我知道我有两种不同状态的相同图像,但即使在模拟器中的一种状态下它也不起作用。谁能指出问题出在哪里?
编辑:
显然正常状态是有效的,因为它从选择器 xml 文件中获取图像。现在我想知道为什么其他州不...
最佳答案
我认为可能与命名有关,所以我将按钮状态图像命名为与 login_button 不同的名称,因为选择器 xml 文件具有相同的名称。我还编辑了我的选择器 xml 文件。
选择器 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Image display in background in select state -->
<item android:state_pressed="true" android:drawable="@drawable/login_btn_down" />
<!-- Image display in background in select state -->
<item android:state_focused="true" android:drawable="@drawable/login_btn_down" />
<!-- Default state -->
<item android:drawable="@drawable/login_btn" />
</selector>
关于android - 为什么我的自定义按钮状态不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5543679/