带有链接的WebViews和.txt文件

时间:2013-11-20 21:55:50

标签: android webview hyperlink

我有一个WebView,我在其中显示.txt文件。这个.txt文件中包含了URL,我想将它们转换为WebView中的链接。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

WebView正在加载文本,就像您的浏览器一样。如果您想要链接,则需要创建一些HTML。一个非常基本的实现看起来像这样:

    StringBuilder sb = new StringBuilder();
    String[] words = plainTextString.split("\\s");  // assume no spaces in links

    sb.append("<html><body>");
    for (String word : words) {
        try {
            // Attempt to add the string as a link
            URL url = new URL(word);
            sb.append("<a href=\"");
            sb.append(url.toString());
            sb.append("\">");
            sb.append(url);
            sb.append("</a> ");
        } catch (MalformedURLException e) {
            // This was not a valid URL, just add it to the string
            sb.append(word);
            sb.append(" ");
        }
    }
    sb.append("</body></html>");

    // Should be able to load this in the WebView
    final String htmlString = sb.toString();