Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set text color to primary android textview

How can I set the text color of my TextView to ?android:textColorPrimary programmatically?

I've tried the code below but it sets the text color always to white for both textColorPrimary and textColorPrimaryInverse (Both of them are not white, I have checked through 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); 
like image 670
jaibatrik Avatar asked Oct 10 '15 06:10

jaibatrik


People also ask

How do I set color programmatically?

To set the color to the TextView widget, call setTextColor() method on the TextView widget reference with specific color passed as argument. setTextColor() method takes int as argument. Use android. graphics.

How do I change the text color on my Android?

Open your device's Settings app . Text and display. Select Color correction. Turn on Use color correction.

How do I add background color to TextView?

To change the background color of TextView widget, set the background attribute with required Color value. You can specify color in rgb , argb , rrggbb , or aarrggbb formats. The background color is applied along the width and height of the TextView.


2 Answers

Finally I used the following code to get the primary text color of the theme -

// 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); 
like image 153
jaibatrik Avatar answered Sep 23 '22 19:09

jaibatrik


You need to check if the attribute got resolved to a resource or a color value.

The default value of textColorPrimary is not a Color but a ColorStateList, which is a resource.

Kotlin solution

@ColorInt fun Context.resolveColorAttr(@AttrRes colorAttr: Int): Int {     val resolvedAttr = resolveThemeAttr(colorAttr)     // resourceId is used if it's a ColorStateList, and data if it's a color reference or a hex color     val colorRes = if (resolvedAttr.resourceId != 0) resolvedAttr.resourceId else resolvedAttr.data     return ContextCompat.getColor(this, colorRes) }  fun Context.resolveThemeAttr(@AttrRes attrRes: Int): TypedValue {     val typedValue = TypedValue()     theme.resolveAttribute(attrRes, typedValue, true)     return typedValue } 

Usage

@ColorInt val color = context.resolveColorAttr(android.R.attr.textColorPrimaryInverse) 
like image 30
zOqvxf Avatar answered Sep 21 '22 19:09

zOqvxf