Android Studio 自定义按钮颜色在形状变化时没有变化

Android Studio custom button color is not changing while shape is changing

我添加了一个自定义按钮,为每个状态更改了一些值,但是当我按下按钮时按钮没有改变,只是获得默认样式,我将矩形的形状更改为椭圆形以便我可以看到如果在选择器中它进入按下状态并且我看到它现在确实进入了唯一的问题是它没有改变的固体或颜色。

自定义按钮实现:

<?xml version="1.0" encoding="utf-8"?>
<item android:state_enabled="false">
    <shape android:shape="rectangle">
        <solid android:color="@color/LightGray"/>
        <corners android:radius="200dp"/>
    </shape>
</item>

<item android:state_pressed="true">
    <color android:color="@color/Blue"/>
    <shape android:shape="rectangle">
        <corners android:radius="200dp"/>
    </shape>
</item>

<item>
    <shape android:shape="rectangle">
        <solid android:color="@color/DarkBlue"/>
        <corners android:radius="200dp"/>
    </shape>
</item>

和按钮实现:

  <Button
    android:id="@+id/btnNext"
    android:layout_width="102dp"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="68dp"
    android:text="Next >"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
   />

按下状态下颜色的位置有问题。纯色 属性 应该在标签内。尝试使用下面

<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <solid android:color="@color/Blue"/>   <-- Move inside Shape
        <corners android:radius="200dp"/>
    </shape>
</item>

它应该按预期工作。

如果上述方法不起作用,请尝试为不同的状态创建不同的可绘制对象:

  1. 启用错误:drawable_1

     <shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle">
    
             <corners android:radius="8dp" />
    
             <solid android:color="@color/LightGray" />
     </shape>
    
  2. 按正确:drawable_2

     <shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle">
    
             <corners android:radius="8dp" />
    
             <solid android:color="@color/Blue" />
     </shape>
    
  3. 按错:drawable_3

     <shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle">
    
             <corners android:radius="8dp" />
    
             <solid android:color="@color/DarkBlue" />
         </shape>
    
  4. 最终将所有可绘制对象与选择器合并

     <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
             <item android:drawable="@drawable/drawable_1" android:state_enabled ="true"></item>
             <item android:drawable="@drawable/drawable_2" android:state_pressed="true"></item>
             <item android:drawable="@drawable/drawable_3" android:state_pressed="false"></item>
    
     </selector>
    

我发现在使用自定义按钮时一定要更改

<Button.../>

<androidx.appcompat.widget.AppCompatButton

这是因为 material io 按钮不能接受自定义按钮作为背景。