Question

I am trying to set different colors for

            str.append(" ").append(isBlue ? "b" : "p");
            SpannableString spannable = new SpannableString(str);
            spannable.setSpan(new ForegroundColorSpan(isBlue ? R.color.blue: R.color.pink),
                    spannable.length() - 1,
                    spannable.length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            miscTextView.setText(spannable);

str is an instance of StringBuilder. I am expecting the last character of miscTextView to be blue if isBlue is true, pink otherwise, while the rest of the text stays black.
But it turns out to be that Either case the last character is grey, which really confuses me. What did I do wrong?

Edit: I check the color resource xml already.Intellij shows the color on the left of xml code line.

Was it helpful?

Solution

You are using R.color.blue which returns the id. You should instead get the color as follows:

getResources().getColor(R.color.blue)

so it will be:

spannable.setSpan(new ForegroundColorSpan(isBlue ? getResources().getColor(R.color.blue): getResources().getColor(R.color.pink)),
                    spannable.length() - 1,
                    spannable.length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

The reason it is gray is because the value of R.color.blue (the id value) maybe an integer corresponding to the color gray.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top