android button点击事件设置背景颜色
时间: 2023-06-02 18:06:57 浏览: 307
好的,关于android button点击事件设置背景颜色的问题,你可以使用以下代码实现:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
button.setBackgroundColor(Color.RED); //设置背景颜色
}
});
希望能够帮助你解决问题。
相关问题
android button自定义点击背景
你可以通过定义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` 中定义的默认背景。
button设置背景颜色
在Android中可以通过设置Button的背景属性来设置Button的背景颜色。有两种方法可以设置Button的背景颜色:
1. 设置背景色:可以使用Button的`setBackgroundColor()`方法来设置Button的背景色,例如:
```java
Button btn = findViewById(R.id.btn);
btn.setBackgroundColor(getResources().getColor(R.color.red));
```
其中,`R.color.red`是一个颜色资源的引用,表示红色。
2. 设置背景Drawable:可以使用Button的`setBackground()`方法来设置Button的背景Drawable,例如:
```java
Button btn = findViewById(R.id.btn);
Drawable drawable = getResources().getDrawable(R.drawable.btn_bg);
btn.setBackground(drawable);
```
其中,`R.drawable.btn_bg`是一个Drawable资源的引用,表示Button的背景Drawable。需要注意的是,设置背景Drawable时,需要将Button的背景色设置为透明色,否则会覆盖背景Drawable,例如:
```java
Button btn = findViewById(R.id.btn);
btn.setBackgroundColor(Color.TRANSPARENT);
Drawable drawable = getResources().getDrawable(R.drawable.btn_bg);
btn.setBackground(drawable);
```
这样就可以设置Button的背景颜色了。