Android中如何用单个Drawable背景文件为多视图设置不同颜色
用单个Drawable实现多视图同背景不同颜色的方案
这里提供两种实用方案,都能让多个视图共用同一个Drawable文件,同时各自显示不同的填充颜色:
方案一:直接使用tint属性(简单快捷)
- 创建基础背景Drawable文件(比如
res/drawable/bg_rounded.xml),定义好固定的样式(圆角、描边等),填充色随便设一个即可(会被tint覆盖):
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="8dp" /> <solid android:color="@android:color/white" /> <!-- 可选:添加描边 --> <stroke android:width="1dp" android:color="@android:color/darker_gray" /> </shape>
- 在布局中给每个视图设置该背景,再通过
android:tint指定不同颜色:
<!-- 红色填充的视图 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_rounded" android:tint="#FF4444" android:text="视图1" /> <!-- 绿色填充的视图 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_rounded" android:tint="#4CAF50" android:text="视图2" /> <!-- 蓝色填充的视图 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_rounded" android:tint="#2196F3" android:text="视图3" />
注意:Android 5.0(API 21)及以上直接支持
android:tint作用于背景;低版本需使用AppCompatTextView并改用app:tint属性。
方案二:自定义属性+主题(兼容性强,便于统一管理)
- 在
res/values/attrs.xml中定义自定义颜色属性:
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="customBgColor" format="color" /> </resources>
- 创建基础背景Drawable文件
res/drawable/bg_rounded.xml,使用自定义属性作为填充色:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="8dp" /> <solid android:color="?attr/customBgColor" /> <stroke android:width="1dp" android:color="@android:color/darker_gray" /> </shape>
- 在
res/values/styles.xml中定义对应颜色的主题:
<style name="CustomBgRed"> <item name="customBgColor">#FF4444</item> </style> <style name="CustomBgGreen"> <item name="customBgColor">#4CAF50</item> </style> <style name="CustomBgBlue"> <item name="customBgColor">#2196F3</item> </style>
- 在布局中给每个视图设置背景并指定对应的主题:
<!-- 红色填充视图 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_rounded" android:text="视图1" android:theme="@style/CustomBgRed" /> <!-- 绿色填充视图 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_rounded" android:text="视图2" android:theme="@style/CustomBgGreen" /> <!-- 蓝色填充视图 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_rounded" android:text="视图3" android:theme="@style/CustomBgBlue" />
内容的提问来源于stack exchange,提问作者HaBuiDuc
相关产品推荐
相关产品推荐

