如何将白色设置为 TextView 中除了 android 中的数字和逗号之外的任何字母?

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

我想为 TextView 中除了数字和逗号之外的任何字母设置白色 然后我想将其他角色的颜色设置为白色。 我该怎么做?

例子

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

您可以使用 Spannable TextView

可以在 Android 中使用 spannable TextView 以不同的颜色、样式、大小、and/or 单击事件突出显示文本的特定部分在单个 TextView 小部件中。

所以试试这个:

    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);

您还可以使用正则表达式如下

Spannable spannable = new SpannableString(myTextView.getText().toString());
// Matching non-digits
Matcher matcher = Pattern.compile("\D+").matcher(text);
while (matcher.find()) {
    spannable.setSpan(new ForegroundColorSpan(Color.WHITE), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

// Matching digits followed by "," 0 or 1 time
matcher = Pattern.compile("\d+,?").matcher(text);
while (matcher.find()) {
    spannable.setSpan(new ForegroundColorSpan(Color.YELLOW), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

myTextView.setText(spannable);