Android: Linkify TextView
I have textview which I need to linkify. Here's what I am doing..
TextView text = (TextView) view.findViewById(R.id.name);
text.setText("Android...Update from Android");
Pattern pattern = Pattern.compile("Android");
String scheme = "www.android.com";
Linkify.addLinks(text, pattern, scheme);
The text-view is displayed correctly with the text "Android...Update from Android", but I am facing two problems.
1) My text string has two instances of the string "Android". So, both the text are linkified. I want only the first occurrence to be linkified. How should I go about it?
2) When I click the linkfy text, it opens the browser, but the URL is weird. The url it tries to open is "www.comandroid". I don't know whats going wrong here. The text "android" in the URL is being replaced. Am I doing something wrong when Linknifying the text.
Any help will be highly appreciated.
The easy way is put autoLink in XML layout.
android:autoLink="web"
I created a static method that does this simply:
/**
* Add a link to the TextView which is given.
*
* @param textView the field containing the text
* @param patternToMatch a regex pattern to put a link around
* @param link the link to add
*/
public static void addLink(TextView textView, String patternToMatch,
final String link) {
Linkify.TransformFilter filter = new Linkify.TransformFilter() {
@Override public String transformUrl(Matcher match, String url) {
return link;
}
};
Linkify.addLinks(textView, Pattern.compile(patternToMatch), null, null,
filter);
}
And the OP could use it simply:
addLink(text, "^Android", "http://www.android.com");