繁体   English   中英

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

[英]How to set the selected text background color of TextView

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

例如:

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


}

输出: 在此输入图像描述

你可以使用一些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));

您应该查看JEditorPane类,它允许您轻松地执行以下操作:

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

在此输入图像描述

这里查看关于设置TextView颜色的这个问题。

您可以使用

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

要么

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

要么

textview1.setBackgroundColor(Color.RED);

要么

textView1.setBackgroundColor(R.color.black);

您可以将文本格式化为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文本

这种格式适用于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>");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM