2015-10-10 18 views
10

Come posso impostare il colore del testo del mio TextView su ?android:textColorPrimary a livello di programmazione?Imposta colore testo su textview Android principale

Ho provato il codice qui sotto, ma imposta il colore del testo sempre sul bianco sia per textColorPrimary che per textColorPrimaryInverse (entrambi non sono bianchi, ho controllato tramite 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

Solitamente estendo la classe TextView e la utilizzo ovunque nell'app. Nella mia classe TextView ho impostazioni come colori, font e così via. Un altro approccio consiste nel creare una variabile statica con il colore desiderato e utilizzare .setTextColor(); ovunque. Terzo modo è utilizzare il nuovo debugger di temi per Android Studio (1.4) per modificare il tema. So che questa non è una risposta diretta, ma potrebbe essere un buon lavoro. –

+0

Non intendo usare 'setTextColor' ovunque. Voglio impostare il colore da secondario a primario per un particolare 'TextView'. – jaibatrik

+0

puoi provare ad usarlo come ... .. 'mTextView.setTextColor (android.R.attr.textColorPrimary);' –

risposta

14

Infine ho usato il seguente codice per ottenere il colore del testo primario del tema -

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

Non dimenticare di riciclare il TypedArray dopo l'ultima riga 'arr.recycle()'. – sorianiv

3

Questo è il modo corretto per farlo.

Il valore predefinito di textColorPrimary non è un colore, ma un ColorStateList, quindi è necessario verificare se l'attributo ottenuto risolto in un ResourceId o di un valore di colore.

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); 
} 
Problemi correlati