Reputation: 13
I've been trying to figure this one out for a bit using patterns or other utils but haven't gotten it to work just yet.
Say I have an HTML link:
<a href="http://www.google.com">Google, Inc.</a>
I want to make a link into a text view BUT set the text of the link as the actual URL not Google, Inc.
So for example if the data I received is:
--Hey if you want to try a search go to <a href="http://www.google.com">Google, Inc.</a>
and it's easy as that.
I want it to display as:
--Hey if you want to try a search go to http://www.google.com and it's easy as that.
Instead of:
--Hey if you want to try a search go to Google, Inc. and it's easy as that.
Html.fromHtml() makes it show as "Google, Inc." automatically, but isn't the result that I want.
Also, I don't need this to work for specifically this example, I need it to work for all html links as I don't know what links I will get as data.
Upvotes: 1
Views: 645
Reputation: 86948
I suggest using Linkify and parsing the Strings yourself to create the links you want.
Set Linkify to look for raw web addresses and turn them into links in your text:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
/>
This function will pull the raw address out the html tags:
public String parseLinks(String raw) {
String openTag = "<a href=\"";
String closeTag = "</a>";
String result = "";
int start = 0;
int middle = raw.indexOf(openTag);
int end;
while(middle > -1) {
result += raw.substring(start, middle);
end = raw.indexOf("\">", middle);
result += raw.substring(middle + openTag.length(), end);
start = raw.indexOf(closeTag, end) + closeTag.length();
middle = raw.indexOf(openTag, start);
}
result += raw.substring(start, raw.length());
return result;
}
Understand that this function does no error checking, I recommend adding this yourself.
Now simply pass the String returned from parseLinks() to your TextView, like this:
textView.setText(parseLinks(rawHTML));
Hope that helps!
Upvotes: 0
Reputation: 4161
it's actually pretty tricky .... but i have found a way to do so.
Thanks to SO for that.
here is the answer:
TextView tvYourTextView = ( TextView ) findById( R.id.yourTextViewThatShowsALink );
tvYourTextView.setMovementMethod(LinkMovementMethod.getInstance()); //that will make your links work.
PS:
Don't forget to use Html.fromHtml("your content as html")
Upvotes: 1