Monday 25 August 2014

Set typeface for webview in android


Set typeface for webview in android :

This is an Example for how to set typeface for webview using html. In this view set the typeface in HTML String and load with webview.  Put the font in assests folder.



Every android device having default font .By using typeface is required to give your application look and feel good.CLICK HERE to know more about typeface

Step :1 create a new Android application project and copy these code into xml file
activity_main.xml: ]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <WebView
        android:id="@+id/webViewFace"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Step :2
create an MainActivity.java in the src folder and copy these code
package com.androidtoppers.typeface;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

 WebView mWebView;
 

 String htmlstr1="<p style='text-align:right'><H2>Android Toppers</H2></p> <p style='text-align:left'>It is safer to use a JSON parser to convert a JSON text to a JavaScript object.</p>";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activtiy_main);
  
  mWebView = (WebView) findViewById(R.id.webViewFace);
  mWebView.setWebViewClient(new WebViewClient() {

   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
    view.loadUrl(url);
    return true;
   }
  });
   String head1 = "<head><style>@font-face {font-family: 'arial';src: url('file:///android_asset/fonts/bichkam.ttf');}body {font-family: 'verdana';}</style></head>";
   String text="<html>"+head1
     + "<body style=\"font-family: arial\">" + htmlstr1
     + "</body></html>";
   
   mWebView.loadDataWithBaseURL("", text, "text/html", "utf-8", "");

 }

}

  Screenshots :

   


DOWNLOAD FULL SOURCE CODE

1 comment:

Anonymous said...

Reading this blog makes me feel good to learn about set typeface for WebViews in android. While exploring WebViews in android, I also found this blog, http://findnerd.com/list/view/How-to-implement-a-WebView-in-Android-Application/4716/, hope this will be helpful for developers to learn implementation of WebViews in android. Being an active member of many android developer forum, I'm continuously looking for informative stuff related to android development. Hope to get more from here.