zoukankan      html  css  js  c++  java
  • 一段文字中的几个keyword显示高亮

    将一段文字中的几个keyword显示高亮

    演示样例:将“我的愿望是当个绿巨人,所以我想让我的皮(derma)肤是绿色”中的”皮肤“显示绿色。


    <span style="font-size:18px;">public class MainActivity extends Activity {
    	private static TextView mTextView;
    	//须要显示的文字
    	private static String keywords="皮(.*)肤";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mTextView=(TextView)findViewById(R.id.tv_moder);
            //调用TextUtilTools类的highlight方法
            SpannableStringBuilder textString = TextUtilTools.highlight(
            		mTextView.getText().toString(), keywords);
            //改动文本显示内容
    		mTextView.setText(textString);       
        }
        
        public static class TextUtilTools {
        	/**
        	 * @param text 要显示的内容
        	 * 
        	 * @param target 要高亮显示的内容
        	 * @param SpannableStringBuilder 相似于String,比String多了能够给文字加入样式(颜色,下划线···)
        	 **/
    		public static SpannableStringBuilder highlight(String text,
    				String target) {
    			SpannableStringBuilder spannable = new SpannableStringBuilder(text);
    			//字体样式
    			CharacterStyle span = null;
    			//将keywords作为一个模板
    			 Pattern pattern=Pattern.compile(keywords);
    			 //匹配器
    		     Matcher matcher =pattern.matcher(mTextView.getText());
    			
    			while (matcher.find()) {
    				span = new ForegroundColorSpan(Color.GREEN);// 须要反复。
    				//设置spannable中的关键字
    				spannable.setSpan(span, matcher.start(), matcher.end(),
    						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    			}
    //			spannable.setSpan(new ClickableSpan() {
    //				@Override
    //				public void onClick(View arg0) {
    //					MethodsExtra.startActivity(mContext,HouseManageActivity.class);}
    //			}, 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    			return spannable;
    		}
    	}
    
    
    }
    </span>
    <span style="font-size:24px;color:#ff0000;">将textView中的几个字显示高亮,最简单的方法:</span>
    <span style="font-size:14px;color:#333333;"></span><pre class="java" name="code">tvHuan.setText(Html.fromHtml("看不清<font color=#ff0000>换一张</font>"))。
    <span style="font-size:24px;color:rgb(255,0,0);">
    </span>

    
    
    啦啦~啦~~啦~~~,今天刚学会的。晒给大家!

    。!

  • 相关阅读:
    文件输出debug
    sweetalert
    js认清this的第一步
    Creating default object from empty value in PHP?
    matplotlib画图
    python解析库
    zabbix监控ssl证书过期时间
    aws 预留实例到期监控
    aws ec2挂载 s3
    aliyun挂载oss
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/6866687.html
Copyright © 2011-2022 走看看