use*_*682 2 java android android-layout
我想将TextView中除数字和逗号以外的任何字母设置为白色,然后将其他字符的颜色设置为White。我该怎么做 ?
例
19,319,931 coins
//19,319,931 should has yellow color.
//coins should has has white color
Run Code Online (Sandbox Code Playgroud)
您可以使用Spannable TextView
可跨度的TextView可在Android中使用,以在单个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);
Run Code Online (Sandbox Code Playgroud)