Android Studio中如何通过代码设置文本颜色为textColorPrimary?
解决动态TextView跟随系统主题切换文本颜色的问题
你的问题出在:代码只在初始化时获取了当前主题对应的静态颜色值(一个int类型的色值),当系统主题切换时,TextView持有的是固定色值,不会自动更新。要让它像硬编码的TextView一样跟随主题变化,需要让TextView关联主题属性的动态引用,而非静态色值。
方案1:使用setTextAppearance(推荐)
直接通过主题样式让TextView继承系统的文本外观配置,包括textColorPrimary的动态切换:
// 应用系统默认文本样式,自动跟随主题变化 tV1.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault);
如果需要更精准控制,可自定义Style(在res/values/styles.xml和res/values-night/styles.xml中统一配置):
<!-- res/values/styles.xml --> <style name="PrimaryTextStyle"> <item name="android:textColor">?android:attr/textColorPrimary</item> </style> <!-- res/values-night/styles.xml 无需额外修改,自动继承主题的textColorPrimary -->
然后在代码中设置:
tV1.setTextAppearance(this, R.style.PrimaryTextStyle);
方案2:直接设置动态ColorStateList
如果只需单独控制文本颜色,可获取主题属性对应的ColorStateList(而非单一色值),它会自动响应主题变化:
// 获取主题中textColorPrimary对应的ColorStateList TypedArray typedArray = getApplicationContext().obtainStyledAttributes( new int[]{android.R.attr.textColorPrimary} ); ColorStateList textColorPrimary = typedArray.getColorStateList(0); typedArray.recycle(); // 记得回收TypedArray // 设置给TextView tV1.setTextColor(textColorPrimary);
注意事项:处理主题切换时的Activity重建
默认情况下,系统主题切换会导致Activity销毁并重建,上述代码会重新执行,自动应用新主题颜色。如果你的Activity在Manifest中配置了android:configChanges="uiMode"避免重建,需重写onConfigurationChanged方法手动更新颜色:
@Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); // 重新获取并设置颜色 TypedArray typedArray = getApplicationContext().obtainStyledAttributes( new int[]{android.R.attr.textColorPrimary} ); ColorStateList textColorPrimary = typedArray.getColorStateList(0); typedArray.recycle(); tV1.setTextColor(textColorPrimary); }
内容的提问来源于stack exchange,提问作者CSAlex
相关产品推荐
相关产品推荐

