In this article, we will see how to use custom fonts in WebView of Android application.The same strategy can be used to display local language contents in WebView.
This application renders the text in a WebView using Chancery font.
This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.4.
1. Create an Android application with the given below details
Application Name : WebViewCustomFont
Project Name : WebViewCustomFont
Package Name : in.wptrafficanalyzer.webviewcustomfont
Minimum Required SDK : API 8 : Android 2.2 ( Froyo )
Target SDK : API 17 : Android 4.2 ( Jelly Bean )
2. Create a directory “fonts” under “assets” directory
3. Download “Chancery” font and copy to the assets/fonts directory
We can download a “Chancery” font from here
4. Update the layout file res/layout/activity_main.xml
<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" tools:context=".MainActivity" > <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_world" /> </RelativeLayout>
5. Create an html file assets/demo.html
<html> <head> <meta http-equiv="content-type" content="text/html;" charset="UTF-8"> <style> /** Specify a font named "MyFont", and specify the URL where it can be found: */ @font-face { font-family: "MyFont"; src: url('file:///android_asset/fonts/BLKCHCRY.TTF'); } h3 { font-family:"MyFont"} </style> </head> <body> <h3> Welcome to CustomFont Demo </h3> </body> </html>
6. Update the MainActivity class in the file src/in/wptrafficanalyzer/webviewcustomfont/MainActivity.java
package in.wptrafficanalyzer.webviewcustomfont; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.webkit.WebView; public class MainActivity extends Activity { WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting reference to WebView of the activity_main layout mWebView = (WebView) findViewById(R.id.webview); // Loading an html page into webview mWebView.loadUrl("file:///android_asset/demo.html"); } @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; } }
7. Running the application
Clik here to view.

Figure 1 : WebView CustomFont Demo in Action
8. Download Source Code
Image may be NSFW.
Clik here to view.

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in
You can hire me on hourly basis or on project basis for Android applications development.
For hiring me, please mail your requirements to info@wptrafficanalyzer.in.
My other blogs
store4js.blogspot.com