androidandroid-dark-themeandroid-color

Programmatically set a view's color to ?android:attr color attributes


I need to programmatically set a view's color to ?android:attr/textColorPrimary which is an attribute from the android's dark theme compatible attributes. Now it is possible to get colorButtonNormal with

R.attr.colorButtonNormal

But not ?android:attr/textColorPrimary and ?android:attr/colorBackground. Is there anyway to also get these attributes programmatically?


Solution

  • You can use android.R.attr.textColorPrimary.

    Something like:

        val typedValue = TypedValue();
        theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
        val color = ContextCompat.getColor(this, typedValue.resourceId)
    

    In Java:

    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(android.R.attr.colorSecondary, typedValue, true);
    int color = ContextCompat.getColor(this, typedValue.resourceId);