[英]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.我想将白色设置为 TextView 中除数字和逗号之外的任何字母,然后我想将其他字符的颜色设置为白色。 How can I do it?
我该怎么做?
Example例子
19,319,931 coins
//19,319,931 should has yellow color.
//coins should has has white color
You can use Spannable TextView您可以使用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.可在Android中使用可扩展的 TextView 以在单个 TextView 小部件中以不同的颜色、样式、大小和/或单击事件突出显示文本的特定部分。
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);
You can also use Regular expressions as follows您还可以使用正则表达式,如下所示
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.