How to change font face of Webview in Android?

前端 未结 14 1302
北荒
北荒 2020-11-22 12:23

I want change the default font of webview to a custom font. I\'m using webview in developing an bilingual browser app for Android.

I tried getting an instance of cus

14条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 12:43

    It can be done in Android. I took three days to solve this issue. But now it seems very easy. Follow these steps to set custom font for Webview

    1.Add your font to assets folder
    2.Copy the font to application's files directory

    private boolean copyFile(Context context,String fileName) {
            boolean status = false;
            try { 
                FileOutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
                InputStream in = context.getAssets().open(fileName);
                // Transfer bytes from the input file to the output file
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                // Close the streams
                out.close();
                in.close();
                status = true;
            } catch (Exception e) {
                System.out.println("Exception in copyFile:: "+e.getMessage());
                status = false;
            }
            System.out.println("copyFile Status:: "+status);
            return status;
        }
    

    3.You have to call above function only once (you have to find some logic for this).

    copyFile(getContext(), "myfont.ttf");
    

    4.Use the below code to set value for your webview. Here I am using CSS to set font.

    private String getHtmlData(Context context, String data){
        String head = "";
        String htmlData= ""+head+""+data+"" ;
        return htmlData;
     }
    

    5.You can call the above function as below

    webview.loadDataWithBaseURL(null, getHtmlData(activity,htmlData) , "text/html", "utf-8", "about:blank");
    

提交回复
热议问题