Android TextView Html超链接实现自定义点击事

2020-04-09  本文已影响0人  Yuri_Xia

第一步:自定义ClickableSpan


   private static class MyURLSpan extends ClickableSpan {
        private String mUrl;

        MyURLSpan(String url) {
            mUrl = url;
        }

        @Override
        public void onClick(View widget) {
            XLog.d(mUrl);
        }
    }

第二步:处理html

        String text = "请点击<a href=\"http://www.baidu.com\"> 百度 </a>查看详情";
        Spanned spanned = Html.fromHtml(text);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(spanned);
        URLSpan[] urls = spannableStringBuilder.getSpans(0, spanned.length(), URLSpan.class);
        for (URLSpan url : urls) {
            MyURLSpan myURLSpan = new MyURLSpan(url.getURL());
            int start = spannableStringBuilder.getSpanStart(url);
            int end = spannableStringBuilder.getSpanEnd(url);
            int flags = spannableStringBuilder.getSpanFlags(url);
            spannableStringBuilder.setSpan(myURLSpan, start, end, flags);
            //一定要加上这一句,看过很多网上的方法,都没加这一句,导致ClickableSpan的onClick方法没有回调,直接用浏览器打开了
            spannableStringBuilder.removeSpan(url);
        }

第三步:设置给textView

        textView.setText(spannableStringBuilder);
        //这一句加上以后才能处理点击
        textView.setMovementMethod(LinkMovementMethod.getInstance());

至此就能首先自定义点击了。

上一篇下一篇

猜你喜欢

热点阅读