您好,我正在开发演示应用程序,我需要在字符串中设置所选文本的黄色背景色。
例如:
String str = "Na Adam ne ne yere Hawa: Na Adam xwoo xbabarima";
我想为除Adam
之外的所有单词设置白色背景色。我需要将 Adam
单词的背景颜色设置为黄色。
提前致谢。
最佳答案
使用以下代码:
String str = "Na Adam ne ne yere Hawa: Na Adam xwoo xbabarima";
String stringToColor = "Adam";
int ofe = str.indexOf(stringToColor,0);
Spannable WordtoSpan = new SpannableString(str);
for(int ofs=0;ofs<str.length() && ofe!=-1;ofs=ofe+1)
{
ofe = str.indexOf(stringToColor,ofs);
if(ofe == -1)
break;
else
{
WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW), ofe, ofe+stringToColor.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
}
}
输出:
关于java - 如何设置TextView选中的文字背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24998580/