Android UI How to - Dynamically create an HTML string and load it into the WebView








The following code shows how to dynamically create an HTML string and load it into the WebView.

Example

Main layout xml file

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
            android:orientation="vertical" >

        <WebView android:id="@+id/webview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

      </LinearLayout>

In the MainActivity.java file, add the following statements:

        import android.app.Activity;
        import android.os.Bundle;
        import android.webkit.WebSettings;
        import android.webkit.WebView;
// w  ww.  ja va 2  s .c  o  m
        public class MainActivity extends Activity {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

              WebView wv = (WebView) findViewById(R.id.webview1);
              final String mimeType = "text/html";
              final String encoding = "UTF-8";
              String html = "<H1>A simple HTML page</H1><body>" +
                  "<p>The quick brown fox jumps over the lazy dog</p>" +
                  "</body>";
              wv.loadDataWithBaseURL("", html, mimeType, encoding, "");

            }
        }
null