编程设置文本颜色为主要的android TextView的

问题描述:

如何设置我的TextView?android:textColorPrimary编程的文本颜色?编程设置文本颜色为主要的android TextView的

我试过下面的代码,但它将textColorPrimary和textColorPrimaryInverse(它们都不是白色,我已通过XML检查)始终将文本颜色设置为白色。

TypedValue typedValue = new TypedValue(); 
Resources.Theme theme = getActivity().getTheme(); 
theme.resolveAttribute(android.R.attr.textColorPrimaryInverse, typedValue, true); 
int primaryColor = typedValue.data; 

mTextView.setTextColor(primaryColor); 
+0

通常我扩展TextView类,并在应用程序中随处使用它。在我的TextView类中,我设置了诸如默认颜色,字体等。另一种方法是制作一个具有所需颜色的静态变量并使用.setTextColor();到处。第三种方法是使用新的Android Studio(1.4)主题调试器来编辑您的主题。我知道这不是直接的答案,但它可能是一个很好的解决办法。 –

+0

我不打算在任何地方使用'setTextColor'。我想为特定的“Te​​xtView”设置从辅助到主要的颜色。 – jaibatrik

+0

你可以尝试使用它作为... ..'mTextView.setTextColor(android.R.attr.textColorPrimary);' –

最后我用下面的代码来获取主题的主要文本颜色 -

// Get the primary text color of the theme 
TypedValue typedValue = new TypedValue(); 
Resources.Theme theme = getActivity().getTheme(); 
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true); 
TypedArray arr = 
     getActivity().obtainStyledAttributes(typedValue.data, new int[]{ 
       android.R.attr.textColorPrimary}); 
int primaryColor = arr.getColor(0, -1); 
+5

不要忘记在最后一行'arr.recycle()'之后回收TypedArray。 – sorianiv

这是做了正确的道路。

默认值textColorPrimary不是Color而是ColorStateList,因此您需要检查该属性是否已解析为resourceId或颜色值。

public static TypedValue resolveThemeAttr(Context context, @AttrRes int attrRes) { 
    Theme theme = context.getTheme(); 
    TypedValue typedValue = new TypedValue(); 
    theme.resolveAttribute(attrRes, typedValue, true); 
    return typedValue; 
} 

@ColorInt public static int resolveColorAttr(Context context, @AttrRes int colorAttr) { 
    TypedValue resolvedAttr = resolveThemeAttr(context, colorAttr); 
    // resourceId is used if it's a ColorStateList, and data if it's a color reference or a hex color 
    int colorRes = resolvedAttr.resourceId != 0 ? resolvedAttr.resourceId : resolvedAttr.data; 
    return ContextCompat.getColor(context, colorRes); 
}