zoukankan      html  css  js  c++  java
  • android 如何让文本中某个关键字高亮显示?

    TextView tv = (TextView) findViewById(R.id.hello);
    SpannableString s = new SpannableString(getResources().getString(R.string.linkify));

    Pattern p = Pattern.compile("abc");


    Matcher m = p.matcher(s);

    while (m.find()) {
    int start = m.start();
    int end = m.end();
    s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    tv.setText(s);

    /*******************************************************/
     
    1. SpannableStringBuilder style = new SpannableStringBuilder("test Height light");
    2. //参数一:高亮颜色[ForegroundColorSpan前景色]
    3. //from:高亮开始
    4. //to:高亮结束
    5. style.setSpan(new ForegroundColorSpan(color), from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    6. (TextView)view.setText(style);
     /*******************************************************/
    可以使用以下两种方法来实现:

    1.用Html类的fromHtml()方法格式化要放到TextView里的文字。这种方法不仅能够高亮部分文字,而且还能够使用HTML里面方式来格式化文字,显示出各种效果。

    1. TextView.setText(Html.fromHtml("<font color=#FF0000>hello</font>"));
     

    上述代码把hello设置成红色。
    2.使用Spannable或实现它的类,如SpannableString。Spannable对象也可以实现一样的效果

    1. SpannableString ss = new SpannableString("abcdefgh");
    2. ss.setSpan(new BackgroundColorSpan(Color.RED), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    3. TextView.setText(ss);
     

    上述代码把[2,4)之间的字符设置成红色,也就是c和d。

     
     
  • 相关阅读:
    Linux_Bash脚本基础
    Linux_Bash脚本基础
    Windows perl dbi oracle环境配置
    第八章 引用:
    bless 概念
    电力企业信息化建设解决方案之计量生产分析系统
    Tom和Jerry来了,Tom和Jerry走了——北漂18年(38)
    电力企业信息化建设解决方案之计量生产分析系统
    请用fontAwesome代替网页icon小图标
    Python Module_openpyxl_处理Excel表格
  • 原文地址:https://www.cnblogs.com/cmblogs/p/4704724.html
Copyright © 2011-2022 走看看