How to change foreground & background colors in a webview.

Ravi

At times we need to change the font or background color of the webview in Android to make it more readable or to conform to a design of your app. This post will show how simple it can be for an android app builder to almost. The latter is more simple as webview provides an API :

setBackgroundColor (int color)

What one must note is if the HTML contains a value for the background it will override the color we set. The same is true for the foreground color too.

For the foreground color we make use of CSS to set the color and add it to the content we want to display in a div element wrapping the html we need to display. Here is the sample code

private final String htmlbegin = "<div style=\"color:#FFFFFF ;  \">";
private final String htmlend = " </div>";
private final String htmlBody = "<p>Summary</p>"
	+ "<p>Strong text</strong> Somemore text"
	+ "and the final line</p>";
WebView body;

@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	body = (WebView) findViewById(R.id.message_body);
	body.setBackgroundColor(0);

	// body.setDef
	body.loadDataWithBaseURL("", htmlbegin + htmlBody + htmlend,
		"text/html", "utf-8", "");
}

As I stated before any css inside the html will override our css settings.

about the author

Ravi

  1. web development bangalore

    April 28, 2011

    i phone applications are very hard to create, thanks for sharing this code.

  2. dressesforbest

    February 22, 2013

    Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed surfing around your blog posts. After all I¡¯ll be subscribing to your rss feed and I hope you write again soon!

  3. Shanita Grassie

    July 4, 2013

    So beautiful! I love the earthy & classic tones on the wedding! I am so stealing the succulent idea. Beautiful bride, handsome hubby & bridal party. Awesome pics as often Tammy!