android button自定义点击背景
时间: 2023-10-18 13:21:57 浏览: 97
你可以通过定义drawable文件来自定义Android Button的点击背景。以下是一个简单的示例:
首先,创建一个名为 `button_bg.xml` 的 drawable 文件,它将作为按钮的背景。在该文件中添加以下内容:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/button_normal"/>
</selector>
```
在此示例中,使用了 `selector` 标签来定义按钮的状态,并在不同状态下使用不同的 drawable。具体来说,当按钮被按下时,将使用名为 `button_pressed` 的 drawable;否则,将使用名为 `button_normal` 的 drawable。
接下来,创建 `button_pressed.xml` 和 `button_normal.xml` 两个 drawable 文件,分别用于按钮按下和未按下状态的背景。这些文件可以根据你的需求进行定制。
例如,可以创建一个简单的 `button_pressed.xml` 文件,如下所示:
```xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FF4081"/>
</shape>
```
此文件中,使用 `shape` 标签来定义一个矩形形状,并使用 `solid` 标签来填充矩形颜色。在此示例中,填充颜色为粉红色。
最后,在你的布局文件中,将按钮的背景设置为 `button_bg.xml`:
```xml
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!"
android:background="@drawable/button_bg"/>
```
在此示例中,使用 `android:background` 属性将按钮的背景设置为 `button_bg.xml`。现在,当按钮被按下时,它会使用 `button_pressed.xml` 中定义的粉红色背景。否则,它将使用 `button_normal.xml` 中定义的默认背景。
阅读全文
相关推荐

















