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);
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.
Open your device's Settings app . Text and display. Select Color correction. Turn on Use color correction.
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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With