Android's Ttextview is very powerful, we can not only set plain text for its content, but also can set the content containing the URL and e-mail address, and make these clicks can be clicked. But we can capture and control the click events of these links, of course.
This article describes a super simple example of how to implement a click event that captures links in the Android TextView.
Key implementation
The principle of implementation is to set all URLs to Clickspan, and then add the control logic you want to the OnClick event.
Copy Code code as follows:
private void Setlinkclickable (final Spannablestringbuilder Clickablehtmlbuilder,
Final Urlspan Urlspan) {
int start = Clickablehtmlbuilder.getspanstart (Urlspan);
int end = Clickablehtmlbuilder.getspanend (Urlspan);
int flags = Clickablehtmlbuilder.getspanflags (Urlspan);
Clickablespan Clickablespan = new Clickablespan () {
public void OnClick (view view) {
Do something with URLs here.
}
};
Clickablehtmlbuilder.setspan (Clickablespan, start, end, flags);
}
Private charsequence getclickablehtml (String html) {
spanned spannedhtml = html.fromhtml (Html);
Spannablestringbuilder Clickablehtmlbuilder = new Spannablestringbuilder (spannedhtml);
urlspan[] urls = Clickablehtmlbuilder.getspans (0, Spannedhtml.length (), urlspan.class);
For (final Urlspan span:urls) {
Setlinkclickable (Clickablehtmlbuilder, span);
}
return clickablehtmlbuilder;
}
How to use
Copy Code code as follows:
TextView Mytextview = (TextView) Findviewbyid (R.id.mytextview);
String URL = "This is a page with lots of URLs." <a href=\ "http://jb51.net\" >jb51.net</> "+
"This is a very good blog. There are so many great blogs There. can find what "+
"You are want in that blog."
+ "The Next Link is <a href=\" http://www.google.com.hk\ ">google hk</a>";
Mytextview.settext (getclickablehtml (URL));
To achieve their own control
We need to add our own control logic to the Clickspan onclick method, for example, we use the browser to open the click link.
Copy Code code as follows:
public void OnClick (view view) {
LOG.I (LogTag, "OnClick url=" + urlspan.geturl ());
Intent Intent = new Intent (Intent.action_view);
Intent.setdata (Uri.parse (Urlspan.geturl ()));
Intent.setpackage ("Com.mx.browser");
StartActivity (Intent);
}
Remind
Don't forget to set the TextView Autolink property.
Copy Code code as follows:
<textview
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "@string/hello_world"
Android:id= "@+id/mytextview"
android:autolink= "Web"
/>