Android web view loads html pictures and adapts the screen size of mobile phones & click to view the big picture

Posted by laknal on Sun, 30 Jun 2019 22:08:05 +0200

In our development, when displaying the details of information, the background usually gives the html text, and the android side usually uses the webview control to display it. But the html text given by the background is usually used for the computer side, and there is no self-adapting mobile phone, which leads to the display of the picture on the mobile side is too large and needs to move left and right to view the full picture. Below are several practical methods to display pictures in html with webview on the mobile terminal, and to adapt to the display of mobile screen.

It is necessary to display html text with webview control. In order to make the text adapt to the screen size of mobile phone, it is necessary to set the attributes of android webview control. Here bindingView.contentWv stands for webview control.

WebSettings webSettings = bindingView.contentWv.getSettings();//Get the webview settings properties
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//Enlarging the content in html into a column equal to the width of webview
webSettings.setJavaScriptEnabled(true);//Support js
webSettings.setBuiltInZoomControls(true); // Display zoom-in and zoom-out
webSettings.setSupportZoom(true); // Scalable

Here are three commonly used methods:

Method 1: Directly replace the image size under img tag in html text

If the image in html is not set size, you can use the following simple method to set the width and height of the image, but the image may be deformed.

content.replace("<img", "<img height=\"250px\"; width=\"100%\"");

Method 2: Use Jsoup to find img tags and replace the width and height of images

Implementation steps:

1. Import the jsoup package

compile 'org.jsoup:jsoup:1.10.2'

2. Add img tag replacement function to the code

    /**
      * Change the width of the image with img tag in html text content to screen width, and the height adapts to the width ratio.
    **/
public static String getNewContent(String htmltext){
        try {
            Document doc= Jsoup.parse(htmltext);
            Elements elements=doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width","100%").attr("height","auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }

3. Call the replacement function when loading content in webview

bindingView.contentWv.loadDataWithBaseURL(null, getNewContent(content), "text/html", "utf-8", null);

Note that when confusing a project, you need to add the phrase'- keep class org.jsoup. *', otherwise you will make a mistake.*

Using this method, third-party libraries need to be introduced, but the use is relatively simple.

Method 3: Using js script, reset the width and height of the image in img tag

This method needs to use js, and the following sentence must be added to the fixed webview settings property

webSettings.setJavaScriptEnabled(true);//Support js

Implementation steps:

1. Reset WebViewClient for webview

bindingView.contentWv.setWebViewClient(new MyWebViewClient());
bindingView.contentWv.addJavascriptInterface(new JavaScriptInterface(this), "imagelistner");//This is to set up click monitor for pictures. If you need pictures in webview for your project, Click to view large pictures, you can add this function.

2. Rewriting the onPage Finished method of WebViewClient

private class MyWebViewClient extends WebViewClient {

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        imgReset();//Reset the image size of img tags in webview
        // After loading html, add the click js function to listen for pictures
        addImageClickListner();
    }

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

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

If you only need pictures to match the screen size of your mobile phone, it's over now and you've finished the task, and you don't need to add the addImageClickListner() method to onPageFinished in the webviewClient, click on the webview picture to see the big picture as described below.

3. Click on Details Pictures to View Big Pictures

(1) Inject js script and set the image click function openImage

private void addImageClickListner() {
        // The function of this js function is to traverse all img nodes and add onclick function. The function of this function is to call the local java interface and pass the url to the past when the picture is clicked.
        bindingView.contentWv.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }

(2) Achieving Click Events

public static class JavaScriptInterface {

    private Context context;

    public JavaScriptInterface(Context context) {
        this.context = context;
    }

    //Click on Picture Callback Method
    //Annotations must be added or they cannot be responded to
    @JavascriptInterface
    public void openImage(String img) {
        Log.i("TAG", "Response to click events!");
        Intent intent = new Intent();
        intent.putExtra("image", img);
        intent.setClass(context, BigImageActivity.class);//BigImage Activity looks at the classes in the big picture and defines them by itself.
        context.startActivity(intent);
    }
}

Let's look at the actual effect:
Figure 1 below shows that there is no adapted picture display effect. It may be seen that the picture is not fully displayed. It needs to move left and right to view the full picture.

Figure 2 below represents the image display effect after adaptation:

It can be seen that the effect is quite obvious, and the adaptation effect is very good.

summary

The three methods mentioned above can achieve the size of the screen of the mobile phone for picture adaptation in webview, but the three methods are mostly implemented by the third method. Although the use is more complex, it does not need to introduce third-party libraries to facilitate control.

Topics: Mobile Android Javascript Java