如何为自定义按钮设置单击状态?

Guy*_*Guy 5 xml eclipse android

我为按钮创建了自己的背景,我希望按钮在单击时更改.我找到了这段代码:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/boutonnpousse" android:state_pressed="true"/>
<item android:drawable="@drawable/boutonn"/>
</selector>
Run Code Online (Sandbox Code Playgroud)

但是我在哪里使用它?我尝试在主XML文件中粘贴它,但它无法正常工作.

Vik*_*ram 3

您将其保存为文件夹中的 xml 文件res/drawable。如果该文件夹不存在,请创建它。在示例中,我使用的文件名是selector_drawable_name.xml

接下来,每当您使用 Button 并希望其具有单击效果时,请将其背景设置为以下可绘制对象:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1"
    android:background="@drawable/selector_drawable_name" />
Run Code Online (Sandbox Code Playgroud)

结果:当按钮状态变为 时state_pressed,选择的背景为@drawable/boutonnpousse。默认值(在所有其他状态下)将为@drawable/boutonn