如何设置TextView的选定文本背景颜色

时间:2014-07-28 15:23:10

标签: java android

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

例如:

String str = "Na Adam ne ne yere Hawa: Na Adam xwoo xbabarima";

我想设置除Adam以外的所有字词的白色背景颜色。我需要将Adam字的背景颜色设置为黄色。

提前致谢。

6 个答案:

答案 0 :(得分:3)

使用以下代码:

        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

答案 1 :(得分:2)

你可以使用一些html:

String adam = "<font color=#FFFF00>Adam</font>";
String str = "Na Adam ne ne yere Hawa: Na Adam xwoo xbabarima";
String newString = str.replaceAll("Adam", adam);
t.setText(Html.fromHtml(newString));

答案 2 :(得分:0)

你应该查看JEditorPane类,它允许你轻松地做这些事情:

JEditorPane editorPane = new JEditorPane("text/html","<font color=\"red\">this will be red</font><font color=\"blue\">, and this will be blue</font>");

enter image description here

答案 3 :(得分:0)

看看这个question here on setting the color of a TextView.

您可以使用

textView1.setTextColor(getResources().getColor(R.color.mycolor))

textview1.setBackgroundColor(Color.parseColor("#ffffff"));

textview1.setBackgroundColor(Color.RED);

textView1.setBackgroundColor(R.color.black);

答案 4 :(得分:0)

您可以将文本格式化为HTML格式,例如:

   String htmlText =  "<font color=#000000>Na </font> <font color=#00FF00>Adam </font> <font color=#000000>ne ne yere Hawa: Na </font> <font color=#00FF00>Adam </font> <font color=#000000>xwoo xbabarima</font>"

    tView.setText(Html.fromHtml(htmlText))

为了使其更具动态性,您可以添加一些正则表达式功能,以识别应该具有不同颜色的ur关键字并创建HTML文本

答案 5 :(得分:0)

此格式适用于JLabel:

JLabel label = new JLabel("<html>Na <font bgcolor='yellow'>Adam</font> ne ne yere Hawa: Na <font bgcolor='yellow'>Adam</font> xwoo xbabarima</html>");
相关问题