在Android开发中,使用shape标签定义控件背景时,solid子标签用于指定背景的填充颜色,其核心属性android:color的引用方式有多种,不同方式对应不同的使用场景,下面逐一介绍具体的用法和注意事项。

直接赋值颜色值
最直接的方式是在android:color属性中直接填写颜色对应的十六进制值,格式为#ARGB或#AARRGGBB,其中A代表透明度,取值范围是00到FF,00表示完全透明,FF表示完全不透明。
示例代码如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 不透明红色 -->
<solid android:color="#FFFF0000" />
<!-- 半透明蓝色 -->
<solid android:color="#800000FF" />
</shape>
引用colors.xml中的颜色资源
为了统一管理颜色,避免硬编码,通常会把颜色定义在res/values/colors.xml文件中,然后在shape的solid标签中通过@color/颜色名的方式引用。
首先在colors.xml中定义颜色:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="primary_color">#FF6200EE</color>
<color name="secondary_color">#FF03DAC5</color>
</resources>
然后在shape文件中引用:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/primary_color" />
</shape>
引用主题中的颜色属性
如果颜色是跟随应用主题变化的,比如暗黑模式下的背景色,可以引用主题中定义的颜色属性,格式为?attr/属性名或者?属性名。
首先在主题中定义颜色属性:
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<item name="custom_bg_color">@color/primary_color</item>
</style>
然后在shape中引用主题属性:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="?attr/custom_bg_color" />
</shape>
常见错误说明
- 不要漏写颜色值的#号,否则会报资源找不到的错误。
- 引用colors.xml中的颜色时,不要写成
@colors/颜色名,正确的资源类型是color。 - 如果引用的是主题属性,不要写成
@attr/属性名,主题属性引用使用?开头而不是@。
动态修改solid颜色
如果需要在代码中动态修改shape背景的solid颜色,可以通过获取GradientDrawable对象后调用setColor方法实现,示例如下:
// 获取控件的背景,强转为GradientDrawable GradientDrawable drawable = (GradientDrawable) textView.getBackground(); // 设置新的颜色,参数可以是颜色值或者资源id drawable.setColor(ContextCompat.getColor(this, R.color.secondary_color));
Android_shapesolid_colorXML_backgroundcolor_reference修改时间:2026-07-17 15:57:27