Search code examples
javaandroidandroid-layouttextview

how to set white color to any letter in TextView except numbers and commas in android?


I want to set white color to any letter in TextView except numbers and commas and Then I want to set the color of other charactors to White . How can I do it ?

Example

19,319,931 coins
//19,319,931 should has yellow color.
//coins should has has white color

Solution

  • You can use Spannable TextView

    A spannable TextView can be used in Android to highlight a particular portion of text with a different color, style, size, and/or click event in a single TextView widget.

    So Try this :

        String coinText = txtDiamonds.getText().toString();
        char currentChar;
        Spannable spannable = new SpannableString(coinText);
        ForegroundColorSpan color;
        for (int i = 0; i < coinText.length(); i++) {
            currentChar = coinText.charAt(i);
            if (Character.isDigit(currentChar) || ((int) currentChar) == ((int) ','))
                color = new ForegroundColorSpan(Color.YELLOW);
            else
                color = new ForegroundColorSpan(Color.WHITE);
            spannable.setSpan(color, i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        txtDiamonds.setText(spannable);