Using Custom Fonts in Android Webview

by Sasikumar 2014-05-31 11:02:42

To use custom fonts in android webview do the following in corresponding files as shown below,

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/myWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Custom Font Demo @ Hiox.org" />
 
</RelativeLayout>

assets/mywebview.html

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;" charset="UTF-8">
            <style>
                @font-face {
                    font-family: "NameOfFont";
                    src: url('file:///android_asset/fonts/fontfilename.TTF'); /* place fontfilename.ttf in assets/fonts folder */
                }
                h3 { font-family:"NameOfFont"}
            </style>
    </head>
    <body>
        <h3> Custom Font Demo @ Hiox.org </h3>
    </body>
</html>

mainactivity.java

package com.hiox.hioxcustomfont;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
 
public class MainActivity extends Activity {
 
    WebView myFirstWebView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        myFirstWebView = (WebView) findViewById(R.id.myWebView);
        myFirstWebView.loadUrl("file:///android_asset/mywebview.html");
    }
}
Output:

 
944
like
0
dislike
0
mail
flag

You must LOGIN to add comments