android 自定义TextView中Html超链接点击事件详解

public class TextHtmlActivity extends Activity {
    private TextView text;
    private Activity mActivty;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_html_layout);
        mActivty = this;
        text  = (TextView) findViewById(R.id.text);
        text.setText(Html.fromHtml("text3:  " +
                "Text with a " + "link " +
                "点击这个连接---"+
                "连接 "+
                "created in the Java source code using HTML."));
        text.setMovementMethod(LinkMovementMethod.getInstance());
        CharSequence str = text.getText();
        if(str instanceof Spannable){
            int end = str.length();
            Spannable sp = (Spannable)text.getText();  //构建Spannable对象、继承Spanned、Spanned对象继承CharSequener
            URLSpan[] urls=sp.getSpans(0, end, URLSpan.class);  //找出text中的a标签
            //SpannableStringBuilder、SpannableString对象跟String对象差不多、只是比String对象多setSpan,
            //可以给字符串设置样式、大小、背景色...而 SpannableStringBuilder跟SpannableString的关系就跟String跟StringBuffer关系一样
            SpannableStringBuilder style=new SpannableStringBuilder(str);
            style.clearSpans();//should clear old spans
            for(URLSpan url : urls){
                MyClickSpan myURLSpan = new MyClickSpan();
                //设置样式其中参数what是具体样式的实现对象,start则是该样式开始的位置,end对应的是样式结束的位置,
                // 参数 flags,定义在Spannable中的常量
                style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            text.setText(style);
        }

    }
    private class MyClickSpan extends ClickableSpan{
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
            super.updateDrawState(ds);
        }
        @Override
        public void onClick(View widget) {
            Toast.makeText(mActivty,"click link",Toast.LENGTH_SHORT).show();
        }
    }
}

你可能感兴趣的:(android)