If I have a string like:
String textWithUrl = "I am a string and http://www.google.com is the url to google";
Then I put it in a HTML Element:
HTML html = new HTML(textWithUrl);
But the link is not clickable. Usually I make it clickable with (never tested it with a Label
):
private String makeUrlInTextClickable(String text) {
if (text == null) return "";
String[] words = text.split(" ");
String textWithUrl = text;
for (String word : words) {
// Maybe more checks are needed to prevent typos like abcdhttp://
// Mostly the texts come from a source, in which the urls are likely to be valid
if (word.toLowerCase().contains("http://")) textWithUrl = textWithUrl.replace(word, "<a target=\"_blank\" href=\"" + word + "\">" + word + "</a>");
}
return textWithUrl;
}
The textWithUrl
could be of any length with many urls inside.
Is there a better way to do this?
Edit:
Example usage:
public class Test implements EntryPoint {
@Override
public void onModuleLoad() {
String textWithUrl = "I am a string and http://www.google.com is the url to google";
RootPanel.get().add(new HTML(makeUrlInTextClickable(textWithUrl)), 0, 0);
}
}
Output would be then just one HTML Widget with the clickable google url