【问题标题】:Android Button Text Color Always PinkAndroid 按钮文本颜色始终为粉红色
【发布时间】:2017-04-25 06:06:00
【问题描述】:

当按钮在选定状态和非选定状态之间切换时,我正在尝试同时更改按钮文本颜色和按钮背景颜色。背景完美无缺,但文本仅显示为粉红色(默认colorPrimary,我已更改)。

res/drawable/map_button_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <solid android:color="@android:color/transparent"/>
        </shape>
    </item>

    <item android:state_selected="true">
        <shape android:shape="rectangle">
            <corners android:radius="4dp"/>
            <solid android:color="@color/colorPrimary"/>
        </shape>
    </item>
</selector>

res/drawable/map_button_text.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
        <color android:color="@color/colorPrimary"/>
    </item>

    <item android:state_selected="true">
        <color android:color="@android:color/white"/>
    </item>
</selector>

res/styles/styles.xml

<style name="Button.Map">
    <item name="android:layout_height">0dp</item>
    <item name="android:layout_weight">1</item>
    <item name="android:layout_margin">4dp</item>
    <item name="android:background">@drawable/map_button_background</item>
    <item name="android:textColor">@drawable/map_button_text</item>
</style>

此外,文本颜色永远不会改变,它只是一直保持粉红色。我尝试添加 &lt;item android:color="@color:/colorPrimary"/&gt; 作为默认值,但它仍然不起作用。

关于是什么原因的任何想法?

【问题讨论】:

    标签: android xml button state


    【解决方案1】:

    你有一些问题。

    首先,您的&lt;item&gt; 元素应该直接具有android:color 属性,而不是在子&lt;color&gt; 元素中。

    其次,android:textColor 需要引用颜色资源(或文字颜色值)。

    您已将map_button_text 资源放在res/drawable 文件夹中,这会告诉Android 将其解释为Drawable,而不是颜色。

    如果您将该文件移至res/color 并通过@color/map_button_text 引用它,您应该会得到您想要的。

    最后,您还应该为选择器定义一个默认状态(没有任何android:state_ 属性的状态)。

    您的最终 XML 应该如下所示:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@color/colorPrimary" android:state_selected="false"/>
    
        <!-- Default state -->
        <item android:color="@android:color/white"/>
    </selector>
    

    【讨论】:

    • 真棒回答 Bryan,我对此有一些问题,经过我们的一些问题后,我意识到这是因为它所在的目录。它在 res/drawable 而不是 res/color 内。
    猜你喜欢
    • 1970-01-01
    • 2022-11-06
    • 2019-03-28
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多