TextView处理Html文本超链接事件

TextView是Android中用于显示文本的一个普通控件,

textview.setText(“文本”);

同时它也支持Html文本的显示,textview.setText()

textview.setText(Html.fromHtml(""Html文本));

但是针对Html文本仅作显示并不能满足所有需求,当文本中存在超链接是

/**
     * 处理html文本超链接点击事件
     * @param context
     * @param tv
     */
    public static void textHtmlClick(Context context, TextView tv) {
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        CharSequence text = tv.getText();
        if (text instanceof Spannable) {
            int end = text.length();
            Spannable sp = (Spannable) text;
            URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.clearSpans();// should clear old spans
            for (URLSpan url : urls) {
                MyURLSpan myURLSpan = new MyURLSpan(url.getURL(), context);
                style.setSpan(myURLSpan, sp.getSpanStart(url),
                        sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            }
            tv.setText(style);
        }
    }
    private static class MyURLSpan extends ClickableSpan {
        private String mUrl;
        private Context mContext;

        MyURLSpan(String url, Context context) {
            mContext = context;
            mUrl = url;
        }

        @Override
        public void onClick(View widget) {         
            Toast.makeText(mContext,"跳转网页",Toast.LENGTH_SHORT).show();
        }
    }

你可能感兴趣的:(TextView处理Html文本超链接事件)