如何跨模块获取主题颜色并应用到Shape Drawable?
解决Shape Drawable跨模块获取主题颜色的方案
1. 先理清楚模块依赖关系
让Common:view模块依赖Common:ui模块,这样view模块才能访问ui模块里的主题属性定义。在Common:view的build.gradle中添加依赖:
implementation project(":Common:ui")
2. 用对加载Drawable的Context
Shape Drawable里写?attr/colorPrimary本身是可行的,但加载Drawable时别用ApplicationContext,必须使用绑定了当前主题的View Context。比如在自定义View里这么写:
// 错误写法:ApplicationContext无法获取当前主题属性 val wrongDrawable = ContextCompat.getDrawable(applicationContext, R.drawable.your_shape) // 正确写法:使用View自带的Context(已关联当前主题) val correctDrawable = ContextCompat.getDrawable(context, R.drawable.your_shape)
3. 不用写两个Drawable的优化方案
没必要为深浅主题各单独写一个Drawable,用主题属性+原生Drawable配置就能实现切换:
- 先在
Common:ui的主题里定义一个中间属性(如果还没定义):
<attr name="shapePrimaryColor" format="color|reference" /> <!-- 浅色主题关联colorPrimary --> <style name="AppTheme.Light" parent="Theme.MaterialComponents.Light.NoActionBar"> <item name="shapePrimaryColor">?colorPrimary</item> </style> <!-- 深色主题同样关联colorPrimary --> <style name="AppTheme.Dark" parent="Theme.MaterialComponents.Dark.NoActionBar"> <item name="shapePrimaryColor">?colorPrimary</item> </style>
- 然后在Shape Drawable里用这个中间属性作为填充色:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="?attr/shapePrimaryColor" /> <corners android:radius="8dp" /> </shape>
- 如果需要动态切换主题,更新View的主题后重新加载Drawable即可:
view.applyTheme(R.style.AppTheme.Dark) val updatedDrawable = ContextCompat.getDrawable(view.context, R.drawable.your_shape) view.background = updatedDrawable
4. 排查资源跨模块访问限制
如果以上步骤无效,检查Common:ui模块的资源是否被正确导出。在Common:ui的build.gradle中确认资源可被依赖模块访问:
android { defaultConfig { // 按需添加支持的语言,确保资源能被依赖模块获取 resourceConfigurations += ["en", "zh"] } }
内容的提问来源于stack exchange,提问作者Rafael Vidal
相关产品推荐
相关产品推荐

