安卓:在选择禁用的按钮没有显示文字颜色?按钮、颜色、文字

2023-09-04 08:25:57 作者:痞猫少女

我想做一个按钮,一个选择我的按钮,可以有以下状态:

I am trying to make a button with a selector my button can have the following states:

已启用/禁用 pressed /还不是pressed

根据上述的状态。我需要操作按钮的:

According to the states mentioned above. I need to manipulate the button's:

文本颜色 背景图片

我被禁止,因此它应该有残疾人文字颜色和残疾人按钮背景按钮开始了。但我可以看到默认的文字颜色(风格指定),没有背景图片!

The button starts off my being disabled so it should have the disabled textColor and the disabled button background. But I can see the default textColor (specified in style) and NO background image!

下面是我的选择button_selector.xml

Here is my selector button_selector.xml

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="false"
        android:state_enabled="false"
        android:textColor="#9D9FA2"
        android:drawable="@drawable/button" />    

    <item android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/button_pressed"/>

    <item android:state_pressed="true"
        android:state_enabled="false"
        android:textColor="#9D9FA2"
        android:drawable="@drawable/button"/>

    <item android:state_pressed="false"
        android:state_enabled="true"
        android:drawable="@drawable/button"/>    

</selector>

这里是我的按钮声明,在我的layout.xml

And here is my button declaration in the my layout.xml

    <Button android:id="@+id/reserve_button"
        android:text="@string/reserve_button"
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:paddingRight="15dp"
        android:layout_gravity="left"
        style="@style/buttonStyle"
        android:background="@drawable/button_selector" />

最后,这是我的风格(在我的默认文字颜色设置​​)

And finally this is my style (where my default textColor is set)

<?xml version="1.0" encoding="utf-8"?>

 <resources>

     <style name="buttonStyle">
      <item name="android:textStyle">bold</item>
      <item name="android:textColor">#282780</item>
      <item name="android:textSize">18sp</item>
     </style>

</resources>

请帮忙!

推荐答案

您还需要创建的 StateList 文字颜色标识不同的状态。

You need to also create a StateList for text colors identifying different states.

执行以下操作:

在创建水库另一个XML文件\颜色名字类似 text_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <!-- disabled state -->
  <item android:state_enabled="false" android:color="#9D9FA2" /> 
  <item android:color="#000"/>
</selector>

在你的 style.xml ,把一个对 text_color.xml 文件,如下所示:

In your style.xml, put a reference to that text_color.xml file as follows:

<style name="buttonStyle">
  <item name="android:textStyle">bold</item>
  <item name="android:textColor">@color/text_color</item>
  <item name="android:textSize">18sp</item>
</style>

这应该解决您的问题。