如果按钮已经有shape_layout,如何在按下时改变按钮的颜色? Android

How to change color of button when pressed if it already have shape_layout? Android

我想在按下时改变按钮的颜色,但我已经有了

android:background="@drawable/shape_layout"

shape_layout.xml代码:

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

    <gradient android:startColor="#ff055500"
              android:endColor="#ff055500"/>

    <corners android:radius="1dp" />

    <stroke android:width="1px" android:color="#ffffff" />

</shape>

那么如何在按下时改变按钮的颜色?

您还需要两个 XML 文件:

  • shape_layout_hover.xml(基本相同的文件,只是将颜色更改为应该在按下状态下显示的颜色)
  • select或将 select 不同按钮状态下的这两种布局之一的文件。

select或XML的示例:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

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

    <item android:state_focused="true" android:drawable="@drawable/shape_layout_hover" />

    <item android:drawable="@drawable/shape_layout" />
</selector>

然后用select或文件作为背景创建按钮样式。并将该样式设置为按钮项。

<item name="android:background">@drawable/button_selector</item>

您需要创建一个可绘制的选择器:

shape_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_pressed="true" android:drawable="@drawable/shape_layout_pressed"/>
  <item android:state_focused="true" android:drawable="@drawable/shape_layout_focused"/>
  <item android:drawable="@drawable/shape_layout"/>
</selector>

将 pressed/focused 状态所需的颜色添加到新的 XML-drawables,并将 selector-drawable 设置为背景: android:background="@drawable/shape_selector"