如何在任意主题下为指定Fragment获取values-night文件夹中color.xml内的颜色值?
如何让特定Fragment强制获取夜间模式的颜色资源
嘿,这个需求我之前刚好处理过!要让某个Fragment完全无视当前应用/手机的主题模式,直接读取values-night/colors.xml里的colorAppBg,核心思路就是创建一个强制启用夜间模式的Context,用它来获取资源就行。下面给你几种实用的实现方式:
方法一:通过修改Configuration创建夜间Context(推荐,API 24+)
这种方式最直接,通过修改配置强制开启夜间模式,新创建的Context会自动加载values-night下的资源:
Kotlin 实现
// 在你的Fragment中调用 val currentConfig = resources.configuration // 移除原有夜间模式标记,强制设置为夜间模式 val nightConfig = currentConfig.apply { uiMode = uiMode and Configuration.UI_MODE_NIGHT_MASK.inv() or Configuration.UI_MODE_NIGHT_YES } // 创建夜间模式的Context val nightContext = requireContext().createConfigurationContext(nightConfig) // 用这个Context获取颜色,就是values-night里的colorAppBg val nightBgColor = nightContext.getColor(R.color.colorAppBg)
Java 实现
// Java版本代码 Configuration currentConfig = getResources().getConfiguration(); // 重置夜间模式标记,强制开启夜间 Configuration nightConfig = new Configuration(currentConfig); nightConfig.uiMode = (nightConfig.uiMode & ~Configuration.UI_MODE_NIGHT_MASK) | Configuration.UI_MODE_NIGHT_YES; Context nightContext = requireContext().createConfigurationContext(nightConfig); int nightBgColor = ContextCompat.getColor(nightContext, R.color.colorAppBg);
方法二:兼容低版本(API <24)
如果你的应用需要兼容Android 7.0以下的系统,可以用ContextThemeWrapper绑定夜间主题——前提是你已经定义了夜间主题(比如Theme.YourApp.Night),且主题中引用了夜间模式的颜色:
Kotlin 实现
// 绑定夜间主题的Context val nightContext = ContextThemeWrapper(requireContext(), R.style.Theme_YourApp_Night) val nightBgColor = nightContext.getColor(R.color.colorAppBg)
Java 实现
Context nightContext = new ContextThemeWrapper(requireContext(), R.style.Theme_YourApp_Night); int nightBgColor = ContextCompat.getColor(nightContext, R.color.colorAppBg);
注意事项
- 不要长期持有这个
nightContext,用完就回收,避免不必要的内存泄漏。 - 如果你的颜色是通过主题属性(比如
?attr/colorAppBg)定义的,用上面的方法同样能获取到夜间主题下的属性值,原理完全一致。
内容的提问来源于stack exchange,提问作者Marat
相关产品推荐
相关产品推荐

