java - 如何设置TextView选中的文字背景颜色

标签 java android

您好,我正在开发演示应用程序,我需要在字符串中设置所选文本的黄色背景色。

例如:

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


}

输出: enter image description here

关于java - 如何设置TextView选中的文字背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24998580/

相关文章:

Java - 在后台线程中处理计时器事件

java - Java中随便引用方法时的命名约定

android - 如何以编程方式添加联系人?

android - Ionic 2 图像未在 Android 手机中显示

java - 方法不替换所有标签

java - Java Applet 中的 Apache FOP - 未找到数据的 ImagePreloader

java - Gradle 构建失败,:mergeDebugResources 中的 sun.awt.X11GraphicsEnvironment 出现 NoClassDefFoundError

android ImageView setPadding 没有效果

Android 如何使用给定格式 myapp ://http://创建自定义 URL 方案

java - 如何从绑定(bind)的 JTable 中删除行?