SoFunction
Updated on 2025-04-11

Detailed explanation of Android WebView loading html fragments

Here I will briefly describe the requirements: the server returns content with tags on part of the html page.

The solution is: piece together the content fragments returned by the server into a complete page.

The following is the core code:

Here are some configurations of WebView

WebSettings settings = ();
(true);
(true);
(true);
(true);
(new MyWebViewClient(activity));
if (.SDK_INT >= Build.VERSION_CODES.KITKAT) {     
 (.TEXT_AUTOSIZING);
} else {
 ();
}
(getHtmlData(), "text/html;charset=utf-8","utf-8");
private String getHtmlData(String bodyHTML) {
    String head = "<head>" +
        "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
        "<style>html{padding:15px;} body{word-wrap:break-word;font-size:13px;padding:0px;margin:0px} p{padding:0px;margin:0px;font-size:13px;color:#222222;line-height:1.3;} img{padding:0px,margin:0px;max-width:100%; width:auto; height:auto;}</style>" +
        "</head>";
    return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
  }

static class MyWebViewClient extends WebViewClient{
    private WaitingDialog dialog;
    private Activity activity;
    public MyWebViewClient(Activity activity){
      dialog = new WaitingDialog(activity);
       = activity;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      (url);
      (url);
      return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
      (view, url, favicon);
      if(!()) ();
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
      ();
      (view, handler, error);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
      (view, url);
      if(!()) ();
    }

The author occasionally tests on Nexus6 7.0, but the html content cannot be loaded, and the display is blank. After turning on hardware acceleration, it is perfectly solved.

Add the following code to the above WebView settings section

if (()) (true);

How simple it is. I hope it will be helpful to everyone's learning and I hope everyone will support me more.