android设置按钮颜色
时间: 2023-08-22 14:07:16 浏览: 50
在 Android 中,设置按钮的颜色需要使用样式和主题。
首先,在 `res/values/styles.xml` 文件中定义一个样式:
```xml
<style name="ButtonTheme" parent="Theme.AppCompat.Light">
<item name="colorButtonNormal">#2196F3</item>
<item name="android:textColor">#FFFFFF</item>
</style>
```
这里的 `colorButtonNormal` 属性用于设置按钮的默认背景颜色,`android:textColor` 属性用于设置按钮的文字颜色。
然后,在 `res/values/styles.xml` 文件中定义一个主题,将上面定义的按钮样式应用到主题中:
```xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:buttonStyle">@style/ButtonTheme</item>
</style>
```
最后,在 `AndroidManifest.xml` 文件中将上面定义的主题应用到应用程序中:
```xml
<application
android:theme="@style/AppTheme">
...
</application>
```
这样,所有的按钮都会应用上述定义的主题,从而设置按钮的颜色和文字颜色。如果只想设置特定按钮的颜色,可以在布局文件中设置 `android:background` 属性和 `android:textColor` 属性,例如:
```xml
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Button"
android:background="#2196F3"
android:textColor="#FFFFFF" />
```
以上代码中的 `android:background` 属性和 `android:textColor` 属性用于设置按钮的背景颜色和文字颜色。