为什么我的自定义按钮状态不起作用?

时间:2011-04-04 20:03:29

标签: android user-interface android-widget styles

我为我的按钮背景制作了一个自定义的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文件中获取它的图像。现在我想知道为什么其他州不是......

1 个答案:

答案 0 :(得分:5)

我认为可能与命名有关,因此我使用与login_button不同的名称命名按钮状态图像,因为选择器xml文件具有相同的名称。我也编辑了我的选择器xml文件。

Selector 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>
相关问题