0

I have a WebView in which I am displaying a .txt file. This .txt file has URLs listed in it, and I'd like to convert these to links within the WebView. How might I do this?

KairisCharm
  • 1,363
  • 1
  • 13
  • 32

1 Answers1

0

The WebView is loading the text just like your browser would. If you want links, you'll need to create some HTML. A very rudimentary implementation would look like this:

    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();
Krylez
  • 17,414
  • 4
  • 32
  • 41