美文网首页升云的Android记事本
Android-TextView关键字高亮与超链接

Android-TextView关键字高亮与超链接

作者: 升云手札 | 来源:发表于2017-09-11 19:40 被阅读0次

    目的:
    将TextView里文本中的某些关键字高亮,并且设置超链接,可以进行页面的跳转

    实现方法:
    使用SpannableString,采用正则表达来搜索文本中的关键字;
    设置关键字的超链接通过重写ClickableSpan来实现

    // 加载文章内容高亮多个关键字,只高亮一个关键字去掉循环
            String[] keywords = new String[] { "power", "internet" };
            SpannableString s = new SpannableString(getResources().getString(
                    R.string.papercontent));
            for (int i = 0; i < keywords.length; i++) {
                Pattern p = Pattern.compile(keywords[i] + "\\W");
                Matcher m = p.matcher(s);
                while (m.find()) {
                    int start = m.start();
                    int end = m.end() - 1;
                    Intent intent = new Intent(getApplicationContext(),
                            KeyWord.class);
                    s.setSpan(new IntentSpan(intent), start, end,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }
            }
            tvContent.setText(s);
            tvContent.setMovementMethod(LinkMovementMethod.getInstance());
    
    /**
         * 重写ClickableSpan中的onClick,实现点击效果
         * @author zengjiyang
         */
        public class IntentSpan extends ClickableSpan implements ParcelableSpan {
            private Intent mIntent;
    
            public IntentSpan(Intent mIntent) {
                super();
                this.mIntent = mIntent;
            }
    
            @Override
            public int describeContents() {
                // TODO Auto-generated method stub
                return 0;
            }
    
            @Override
            public void writeToParcel(Parcel dest, int flags) {
                // TODO Auto-generated method stub
            }
    
            @Override
            public int getSpanTypeId() {
                // TODO Auto-generated method stub
                return 100;
            }
    
            @Override
            public void onClick(View widget) {
                // TODO Auto-generated method stub
                Context context = widget.getContext();
                context.startActivity(mIntent);
            }
    
            @Override
            public void updateDrawState(TextPaint ds) {
                // TODO Auto-generated method stub
                super.updateDrawState(ds);
                ds.setColor(Color.RED);
                ds.setUnderlineText(false);
                ds.bgColor = Color.TRANSPARENT;
            }
    
        }
    

    相关文章

      网友评论

        本文标题:Android-TextView关键字高亮与超链接

        本文链接:https://www.haomeiwen.com/subject/wpgfsxtx.html