2015-10-10 68 views
10

如何設置我的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);' –

回答

14

最後我用下面的代碼來獲取主題的主要文本顏色 -

// 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

3

這是做了正確的道路。

默認值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); 
} 
相關問題