问题
I want to do something like
Click <a href='www.google.com'>Here</a>
in android. I tried using the following:
TextView sponsoredlink = new TextView(this);
sponsoredlink.setId(R.id.details_sponsored_link);
sponsoredlink.setText("Click Here");
Pattern pattern =Pattern.compile("Here");
String link = "www.google.com";
Linkify.addLinks(sponsoredlink, pattern, link);
but i just end up with a link to www.google.comhere [sic]
回答1:
Just to answer my own question, I found a tutorial on transform filters and adapted it to my own ends:
TextView sponsoredlink = new TextView(this);
sponsoredlink.setId(R.id.details_sponsoredlink);
sponsoredlink.setText("Click Here");
TransformFilter mentionFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return new String("http://www.google.com");
}
};
// Match @mentions and capture just the username portion of the text.
Pattern pattern = Pattern.compile(".");
String scheme = "";
Linkify.addLinks(sponsoredlink, pattern, scheme, null, mentionFilter);
I decided I wanted to turn the whole text into one big link in the end, so I did a pattern that matched the whole text.
Then I created a transform filter which just ignores whatever you give it and returns the URL I wanted to take people to
The scheme also has to be the empty string so nothing gets added on the end
Finally I used linkify to put it all together
来源:https://stackoverflow.com/questions/5249013/android-linkify-a-completely-unrelated-string