一段文字中的几个关键字显示高亮

来源:互联网 发布:李钟硕李敏镐网络剧 编辑:程序博客网 时间:2024/05/22 03:44

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

示例:将“我的愿望是当个绿巨人,所以我想让我的皮(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>


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

0 0
原创粉丝点击