0

I have an EditText in my app that checks the user’s input on each change, and sets the text color to R.color.red_error_text when the input is malformatted. When the input is fine again, the color should change back to the default, which depends on the currently set theme. Is there a way to unset the value, i.e. a code equivalent to clearing the textColor field in the design editor or deleting the corresponding entry from the XML?

Alternatively, can I set the text color to ?attr/textColorPrimary from the code?

I’m aware I can query the currently set theme whenever the color should change, and then set the color manually; but then the code would have to be changed whenever a new theme is introduced or the app’s color scheme changes for some reason.

Any help would be appreciated!

Anypodetos
  • 13
  • 5

1 Answers1

1

I finally found an answer at How can I get the primary color from my app theme?. Translated to Kotlin, the solution is:

fun resolveColor(id: Int): Int {
    val typedValue = TypedValue()
    theme.resolveAttribute(id, typedValue, true)
    return typedValue.resourceId
}

Then we can call

editInput.setTextColor(ContextCompat.getColor(applicationContext,
    resolveColor(R.attr.editTextColor)))

to set the text color in the currently set app theme, including day/night themes. resolveColor(R.attr.someThemeColor) also seems to work for any other color that is defined in the theme.xmls.

Anypodetos
  • 13
  • 5