How to load HTML & CSS string in a WebView

person folder_openAndroidaccess_time March 21, 2015

In the previous tutorial Android WebView Tutorial, we learned about using WebView. Now let’s learn how to load static HTML string content in WebView.
See flowing Steps :

  1. Create a layout file res/layout/activity_main.xml with one WebView in it.
  2. Create a data helper class to generate HTML content with CSS style scripts embedded.
  3. INTERNET permission is not necessary in this case.

Note: Custom WebViewClient is not necessary to load string data.

1. Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stackandroid.htmlcss"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

2. Activity layout file
This layout file contains TextView along with WebView.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hsbc.WebviewActivity" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="HTML and CSS in android"
            android:textColor="#860000"
            android:textSize="23dp"
            android:layout_centerHorizontal="true"
           android:textStyle="bold" />
   <WebView
       android:id="@+id/rawdataWebview"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_alignParentRight="true"
       android:layout_below="@+id/textView1"
       android:layout_marginTop="40dp" />
</RelativeLayout>

3. Main Activity code
Note: Custom WebViewClient is not necessary to load string data. Enable pinch zoom options by setting setBuiltInZoomControls to true.

package com.stackandroid.htmlcss;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		String completeHtmlData = new DataFuncions().generateHtmlData(this);
		WebView mWebView = (WebView)findViewById(
				R.id.rawdataWebview);
		// Add javascript support to the webview
		mWebView.getSettings().setJavaScriptEnabled(true);
		// Enable pinch zoom controls on webview
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.setInitialScale(100);
		mWebView.getSettings().setUseWideViewPort(true);
		// Load the html string data
		mWebView.loadData(completeHtmlData, "text/html", "UTF-8");
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

Then write DataHelper.java class to generate static HTML content along with CSS styles. Like the same way, we can add javascript functions also.

package com.stackandroid.htmlcss;
import android.app.Activity;
import android.util.Log;
public class DataHelper extends Activity{
	StringBuffer html;
	String[] tableContent = {"Name:Tamil:English:Maths:Science:Social Science","Vinoth:93:96:100:98:99", "Kumar:94:99:100:98:98","Raju:95:95:100:94:99", "Bala:96:99:100:98:99","Franklin:94:99:100:98:98", "Jovey:93:96:100:98:99"};
	/**
	 * Generate HTML data and append input data stored in asset text file
	 * @param activity
	 * @return
	 */
	public String generateHtmlData(Activity activity){
			String[] tableArray = null;
			html = new StringBuffer("<html><head>"+getCSSForTable()+"</head>" + "<table class=\"TableStyle\">");
			for(String data : tableContent)
			{
				tableArray = data.split(":");
				html.append("<tr>");
				for (int i = 0; i < tableArray.length; i++) {
					html.append("<td>" + tableArray[i] + "</td>");
					Log.v("table array", tableArray[i]);
				}
				html.append("</tr>");
			}
			html.append("</tr>" + "</table>" + "<br/><br/><div align=\"center\"><<<< Scroll horizontally >>>></div><br/><div align=\"center\">Supports Pinch Zoom</div></html>");
			Log.v("html appended value", html.toString());
		return html.toString();
	}
	/**
	 * Generate CSS styles
	 * @return
	 */
	private String getCSSForTable(){
		String cssString;
		cssString = "<style>"+
		".TableStyle {"+
			"margin:0px;padding:0px;"+
			"width:100%;"+
			"box-shadow: 10px 10px 5px #888888;"+
			"border:1px solid #07214f;"+
			"-moz-border-radius-bottomleft:0px;"+
			"-webkit-border-bottom-left-radius:0px;"+
			"border-bottom-left-radius:0px;"+
			"-moz-border-radius-bottomright:0px;"+
			"-webkit-border-bottom-right-radius:0px;"+
			"border-bottom-right-radius:0px;"+
			"-moz-border-radius-topright:0px;"+
			"-webkit-border-top-right-radius:0px;"+
			"border-top-right-radius:0px;"+
			"-moz-border-radius-topleft:0px;"+
			"-webkit-border-top-left-radius:0px;"+
			"border-top-left-radius:0px;"+
		"}.TableStyle table{"+
		    "border-collapse: collapse;"+
		    "border-spacing: 0;"+
			"width:100%;"+
			"height:100%;"+
			"margin:0px;padding:0px;"+
		"}.TableStyle tr:last-child td:last-child {"+
			"-moz-border-radius-bottomright:0px;"+
			"-webkit-border-bottom-right-radius:0px;"+
			"border-bottom-right-radius:0px;"+
		"}"+
		".TableStyle table tr:first-child td:first-child {"+
			"-moz-border-radius-topleft:0px;"+
			"-webkit-border-top-left-radius:0px;"+
			"border-top-left-radius:0px;"+
		"}"+
		".TableStyle table tr:first-child td:last-child {"+
			"-moz-border-radius-topright:0px;"+
			"-webkit-border-top-right-radius:0px;"+
			"border-top-right-radius:0px;"+
		"}.TableStyle tr:last-child td:first-child{"+
			"-moz-border-radius-bottomleft:0px;"+
			"-webkit-border-bottom-left-radius:0px;"+
			"border-bottom-left-radius:0px;"+
		"}.TableStyle tr:hover td{"+
		"}"+
		".TableStyle tr:nth-child(odd){ background-color:#ffffff; }"+
		".TableStyle tr:nth-child(even)    { background-color:#a6d3ed; }.TableStyle td{"+
			"vertical-align:middle;"+
			"border:1px solid #07214f;"+
			"border-width:0px 1px 1px 0px;"+
			"text-align:left;"+
			"padding:7px;"+
			"font-size:12px;"+
			"font-family:Arial;"+
			"font-weight:normal;"+
			"color:#020101;"+
		"}.TableStyle tr:last-child td{"+
			"border-width:0px 1px 0px 0px;"+
		"}.TableStyle tr td:last-child{"+
			"border-width:0px 0px 1px 0px;"+
		"}.TableStyle tr:last-child td:last-child{"+
			"border-width:0px 0px 0px 0px;"+
		"}"+
		".TableStyle tr:first-child td{"+
				"background:-o-linear-gradient(bottom, #629edb 5%, #003f7f 100%);	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #629edb), color-stop(1, #003f7f) );"+
			"background:-moz-linear-gradient( center top, #629edb 5%, #003f7f 100% );"+
			"filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#629edb\", endColorstr=\"#003f7f\");	background: -o-linear-gradient(top,#629edb,003f7f);"+
			"background-color:#629edb;"+
			"border:0px solid #07214f;"+
			"text-align:center;"+
			"border-width:0px 0px 1px 1px;"+
			"font-size:15px;"+
			"font-family:Arial;"+
			"font-weight:bold;"+
			"color:#ffffff;"+
		"}"+
		".TableStyle tr:first-child:hover td{"+
			"background:-o-linear-gradient(bottom, #629edb 5%, #003f7f 100%);	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #629edb), color-stop(1, #003f7f) );"+
			"background:-moz-linear-gradient( center top, #629edb 5%, #003f7f 100% );"+
			"filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#629edb\", endColorstr=\"#003f7f\");	background: -o-linear-gradient(top,#629edb,003f7f);"+
			"background-color:#629edb;"+
		"}"+
		".TableStyle tr:first-child td:first-child{"+
			"border-width:0px 0px 1px 0px;"+
		"}"+
		".TableStyle tr:first-child td:last-child{"+
			"border-width:0px 0px 1px 1px;"+
		"}"+
		"</style>";
		return cssString;
	}
}

4. Demonstration

Webview HTML & CSS
Webview HTML & CSS

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">