如何在 gwt 中使字符串中的 url 可点击

How to make an url inside a string clickable in gwt

如果我有这样的字符串:

String textWithUrl = "I am a string and http://www.google.com is the url to google";

然后我把它放在一个HTML元素中:

HTML html = new HTML(textWithUrl);

但是 link 不可点击。通常我让它可以点击(从未用 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;
}

textWithUrl 可以是任意长度,里面有很多 url。

有更好的方法吗?

编辑:

用法示例:

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);
    }
}

输出将只是一个 HTML 带有可点击 google url

的小部件

如果要显示 link,则必须使用 锚标记

如果您想使用 HTML 小部件,有 2 个选项:

  1. 制作一串 HTML 代码并将该字符串附加到 HTML 小部件,就像您在代码中所做的那样。
  2. 使用 GWT 提供的任何 HTML 元素(即 HTML 小部件中的 AnchorElement) and wrap it under the HTML widget using wrap() 方法。

希望对您有所帮助。

您可能想到的传统 "link" 样式是锚。它将是蓝色(或浏览器 link 颜色)并带有下划线。点击处理程序将触发您提供的 url。

Anchor link = new Anchor("www.linktositehere.com");

就使用标签实现它而言,您只需创建一个标签并向其添加自定义点击处理程序即可。在您的 uibinder(或 java 代码)中,您可以将标签样式设置为任何您喜欢的样式。

    Label labelLink = new Label("www.linktositehere.com");

    labelLink.addClickHandler(new ClickHandler()
    {

        @Override
        public void onClick(ClickEvent event)
        {
            Window.Location.assign("www.linktositehere.com");
        }
    });

我通常使用以下两种解决方案之一:

1) 如果应用程序中发生某些事情,我会在锚点上设置一个 ClickHandler:

Anchor link = new Anchor("text");
link.addClickHandler(new ClickHandler() {
  @Override
  public void onClick(ClickEvent clickEvent) {
  ...        
  }
});

2) 对于外部链接,打开一个新的浏览器window,我通常只使用以下HTML:

HTML link = new HTML("<a href=\"" + link + "/\" target=\"_blank\">" + text + "</a>");

这不是特定于 GWT 的,但是有大量 JavaScript 库可以满足您的需求。由于您可以简单地从 GWT 中包含和调用 JS,这对您来说应该是一个可行的解决方案。

这里有关于这个主题的 SO 答案:

How to replace plain URLs with links?

但为了完整起见,这些是推荐的库:

两者都有现场演示功能,您可以在其中自行测试。显然,其中 none 将涵盖您的边缘情况,但仍然值得一看。