android中如何设置按钮的背景色
时间: 2024-04-29 08:25:35 浏览: 116
在Android中,可以通过以下方法设置按钮的背景色:
1. 使用xml文件设置背景色:
在res/drawable文件夹下创建一个xml文件,例如button_bg.xml,代码如下:
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/button_color" />
<corners android:radius="5dp" />
</shape>
```
其中,solid标签设置按钮的背景色,corners标签设置按钮的圆角大小。
2. 在布局文件中引用xml文件作为背景:
```
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@drawable/button_bg" />
```
其中,android:background属性设置按钮的背景为button_bg.xml文件。
3. 使用代码设置背景色:
```
Button button = findViewById(R.id.button);
button.setBackgroundColor(ContextCompat.getColor(this, R.color.button_color));
```
其中,setBackgroundColor方法设置按钮的背景色,ContextCompat.getColor方法获取颜色值。可以在res/values/colors.xml文件中定义颜色值,例如:
```
<color name="button_color">#FF4081</color>
```
这样就可以设置按钮的背景色了。
阅读全文
相关推荐


















