自定义 textview上LINK的点击事件

packagecom.TextHtml;

importandroid.app.Activity;
importandroid.content.Context;
importandroid.os.Bundle;
importandroid.text.Html;
importandroid.text.Spannable;
importandroid.text.SpannableStringBuilder;
importandroid.text.method.LinkMovementMethod;
importandroid.text.style.ClickableSpan;
importandroid.text.style.URLSpan;
importandroid.view.View;
importandroid.widget.TextView;
importandroid.widget.Toast;

public class TextHtmlextendsActivity{
/* *Calledwhentheactivityisfirstcreated. */
private TextViewtv;
static Contextctx = null ;
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ctx
= this ;
tv
= (TextView)findViewById(R.id.tv);
StringhtmlLinkText
= " <ahref=\ " http: // www.baidu.com\"><u>我的CSDN博客</u></a>";
tv.setText(Html.fromHtml(htmlLinkText));
tv.setMovementMethod(LinkMovementMethod.getInstance());
CharSequencetext
= tv.getText();
if (textinstanceofSpannable){
int end = text.length();
Spannablesp
= (Spannable)tv.getText();
URLSpan[]urls
= sp.getSpans( 0 ,end,URLSpan. class );
SpannableStringBuilderstyle
= new SpannableStringBuilder(text);
style.clearSpans();
// shouldclearoldspans
for (URLSpanurl:urls){
MyURLSpanmyURLSpan
= new MyURLSpan(url.getURL());
style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(style);
}




}

private static class MyURLSpanextendsClickableSpan{

private StringmUrl;
MyURLSpan(Stringurl){
mUrl
= url;
}
@Override
public void onClick(Viewwidget){
// TODOAuto-generatedmethodstub
Toast.makeText(ctx, " hello! " ,Toast.LENGTH_LONG).show();
}
}
}

你可能感兴趣的:(html,OS)