Thursday, September 5, 2013

Android - Displaying Formatted Text

Bugging me for a while but all you do is:

Step 1: Format the Java String as html
   String formattedMessage = document.replaceAll("(\\r|\\n)", "<br/>");
   formattedMessage = formattedMessage.replaceAll("\\s", "&nbsp;");

Step 2: Display the text in a pre tags
    StringBuilder sb = new StringBuilder();
    sb.append("<html><body><pre>");
    sb.append(formattedMessage);
    sb.append("</pre></body></html>");
    return sb.toString();

Step 3: Display in an AlertDialog using a WebView
   public void showHtml(String html) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(R.drawable.dialog_information);    
    WebView webView = new WebView(this);
    webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    webView.loadData(html, "text/html", "utf-8");
    builder.setView(webView);
    builder.show();
  }   

   

Thursday, May 2, 2013

Regular Expressions (Again! Yes, I have forgotten the basics... meh)

So to match a couple of sub-strings, use this: .*(One|Two|Three|Example).*