Question

I have a String in TextView and I want to Linkify a substring from that string. for example:

click here to know more.

I'm getting the string dynamically. So i have to search if it has click here and convert that to link .How can I linkify "click here".

Was it helpful?

Solution

To find a pattern inside a text and replace it, use this:

Pattern p = Pattern.compile("click here");
Matcher m = p.matcher("for more info, click here");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while(result) {
    m.appendReplacement(sb, "<a href=\"www.mywebsite.com\">click here</a>");
    result = m.find();
}
m.appendTail(sb);
String strWithLink = sb.toString();

yourTextView.setText(Html.fromHtml(strWithLink));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance())

This code will search inside your string and replaces all "click here" with a link.

And at the end, do NOT add android:autoLink="web" to you XML resource (section TextView), otherwise A-tags are not rendered correctly and are not clickable any longer.

OTHER TIPS

did your tried like this

 <a href="www.mywebsite.com">Click here</a>

for setting it to textview  

//get this thru supstring

String whatever="anything dynamically";        
String desc = "what you want to do is<a href='http://www.mysite.com/'>"+whatever+":</a>";


yourtext_view.setText(Html.fromHtml(desc));
String urlink = "http://www.google.com";
String link = "<a href=\"+urlink+ >link</a>"; 
textView.setText(Html.fromHtml(link));

Raghav has the right approach using the fromHtml() method, but if you're searching for for a String with a fixed length, you could do something like:

String toFind = "click here";
if(myString.indexOf(toFind) > -1){
   String changed = myString.substring(0, myString.indexOf(toFind)) + "<a href='http://url.whatever'>" + myString.substring(myString.indexOf(toFind), myString.indexOf(toFind) + toFind.length()) + "</a>" + myString.substring(myString.indexOf(toFind) + toFind.length());
}
else {
   //String doesn't contain it
}

When setting the actual text, you need to use: tv.setText(Html.fromHtml(yourText)); or else it will just appear as a String without any additives. The fromHtml() method allows you to use certain HTML tags inside your application. In this case, the tag which is used for linking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top