Android adapter uses WebView to solve the problem of too large image display after loading



Recently, in the development process, we need to use WebView control to display the details page of the article. The process is to request the background data, and then use the control to load. The article details page returned by the background is directly used by the web page, and there is no adaptation for the mobile terminal. As a result, the pictures displayed in the article details after WebView loading are too large, and it needs to move left and right to view the complete picture Obviously, the user experience is very poor. At this time, we need to adapt the mobile terminal.

Let’s take a look at the effect before adaptation

We can see that only part of the pictures in the loaded article details are shown.

Here’s the solution:

I will not repeat the basic use process of WebView here. This article aims at the situation after loading the details of the article. The method we use here is to reset the width and height of the image in img tag through JS script.

Use steps:

1. This method needs to use js, so the following sentence must be added to the WebView setting attribute, otherwise it is invalid.

webView.getSettings (). Setjavascript enabled (true); // support JavaScript

2. Reset WebView client for WebView

 webView.setWebViewClient(new ArticleWebViewClient());

3. Rewrite the onpagefinished method of webviewclient

private class ArticleWebViewClient extends WebViewClient {

  public void onPageFinished(WebView view, String url) {
   super.onPageFinished(view, url);
   //Reset the image size of img tag in WebView

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

  *Reset the size of the picture, the width is the width of the mobile phone screen, and the height will be automatically scaled according to the width ratio
 private void imgReset() {
  webView.loadUrl("javascript:(function(){" +
    "var objs = document.getElementsByTagName('img'); " +
    "for(var i=0;i<objs.length;i++) " +
    + "var img = objs[i]; " +
    " = '100%'; = 'auto'; " +
    "}" +

Let’s take a look at the effect of the picture on the mobile phone screen


We can see that the effect after adaptation is quite good. The process is to reset the width and height of the image in the IMG tag after loading the page. That’s it.

Well, the above is the whole content of this article, I hope the content of this article has a certain reference learning value for your study or work, thank you for your support for developer.