Search code examples
androidxmlcolorstextviewcolor-palette

Custom colors of TextView are different than Android Studio shows


I have a problem with incorrect TextView colors. I'm using this expression in xml fragment:

android:textColor="@{viewModel.currentColorOfText}"

In ViewModel I use When I'm using currentColorOfText = Color.BLUE everything is okay but when I switch to color defined by myself:

currentColorOfText.value = R.color.blue

TextView is gray (should be blue :))

My defined color in color.xml:

<color name="blue">#0010FF</color>

Thanks in advance


Solution

  • You are fetching a Color Resource ID not a Color value.

    If you open the Colors File you will see that Color.BLUE is a int value:

    @ColorInt public static final int BLUE = 0xFF0000FF;

    To use your Resource Color you will need to pass the context of you Activity/Application(Link to understand which one you should pass).

    Then use the below line of code:

    currentColorOfText.value = ContextCompat.getColor(context, R.color.blue)

    Check Out the StackOverflow answer on how to pass context.