How to change font face of Webview in Android?

前端 未结 14 1147
北荒
北荒 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 = "<head><style>@font-face {font-family: 'verdana';src: url('file://"+ context.getFilesDir().getAbsolutePath()+ "/verdana.ttf');}body {font-family: 'verdana';}</style></head>";
        String htmlData= "<html>"+head+"<body>"+data+"</body></html>" ;
        return htmlData;
     }
    

    5.You can call the above function as below

    webview.loadDataWithBaseURL(null, getHtmlData(activity,htmlData) , "text/html", "utf-8", "about:blank");
    
    0 讨论(0)
  • 2020-11-22 12:44

    You can do it by using CSS. I did it with an app but it won't work in Android 2.1 as there is an known bug with Android browser 2.1.

    0 讨论(0)
  • 2020-11-22 12:45

    There's a working example of this in this project. It boils down to:

    1. In your assets/fonts folder, place the desired OTF or TTF font (here MyFont.otf)
    2. Create a HTML file that you'll use for the WebView's content, inside the assets folder (here inside assets/demo/my_page.html):

      <html>
      <head>
      <style type="text/css">
      @font-face {
          font-family: MyFont;
          src: url("file:///android_asset/fonts/MyFont.otf")
      }
      body {
          font-family: MyFont;
          font-size: medium;
          text-align: justify;
      }
      </style>
      </head>
      <body>
      Your text can go here! Your text can go here! Your text can go here!
      </body>
      </html>
      
    3. Load the HTML into the WebView from code:

      webview.loadUrl("file:///android_asset/demo/my_page.html");
      

    Take note that injecting the HTML through loadData() is not permitted. As per the documentation:

    Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.

    As @JaakL suggests in the comment below, for loading HTML from a string, you should instead provide the base URL pointing to your assets:

    webView.loadDataWithBaseURL("file:///android_asset/", htmlData);
    

    When referencing the font in htmlData, you may then simply use /fonts/MyFont.otf (omitting the base URL).

    0 讨论(0)
  • 2020-11-22 12:48

    If you are putting fonts under res/font like me, then you can change the dir to the following:-

    @font-face {
         font-family: yourfont;
         src: url("file:///android_res/font/yourfont.ttf")
    }
            
    body {
         font-family: yourfont;
    }
    
    0 讨论(0)
  • 2020-11-22 12:49

    Many of the above answers work lie a charm if you have your content in your assets folder.

    However, if you like me want to download and save all your assets from a server to your internal storage you can instead use loadDataWithBaseURL and use a reference to your internal storage as the baseUrl. Then all files there will be relative to the loaded html and are found and used correctly.

    In my internal storage I have saved the following files:

    • IndigoAntiqua2Text-Regular.ttf
    • style.css
    • image.png

    Then I use the following code:

    WebView web = (WebView)findViewById(R.id.webby);
    //For avoiding a weird error message
    web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    
    String webContent = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><link rel=\"stylesheet\" href=\"style.css\"></head>"
                                + "<body><img src='image.png' width=\"100px\"><div class=\"running\">I am a text rendered with INDIGO</div></body></html>";
    
    String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/";
    web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", "");
    

    The CSS file used in the above html (style.css):

    @font-face {
      font-family: 'MyCustomRunning';
      src: url('IndigoAntiqua2Text-Regular.ttf')  format('truetype');
    }
    
    .running{
        color: #565656;
         font-family: "MyCustomRunning";
         font-size: 48px;
    }
    

    I have only tried this while targeting minSdkVersion 19 (4.4) so I have no idea if it works on other versions

    0 讨论(0)
  • 2020-11-22 12:52

    Use https://github.com/delight-im/Android-AdvancedWebView library.

    in html data :

    <!doctype html>
    <html>
    
    <head>
    <style type="text/css">
    @font-face {
        font-family: MyFont;
        src: url("file:///android_asset/fonts/font1.ttf")
    }
    body {
        font-family: MyFont;
        font-size: medium;
        text-align: justify;
    }
    </style>
    <meta http-equiv="Content-Type" content="text/html;  charset=utf-8">
    <title>Title</title>
    </head>
    
    <body>
    
        ------ YOUR_CONTENT ------
    
    </body>
    
    </html>
    

    in xml :

    <im.delight.android.webview.AdvancedWebView
        android:id="@+id/advanced_web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    in java :

    advancedWebView = findViewById(R.id.advanced_web_view);
    advancedWebView.loadHtml(htmlData, "text/html; charset=utf-8", "utf-8");
    
    0 讨论(0)
提交回复
热议问题