Search code examples
androidtextviewandroid-theme

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);

Solution

  • 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);