Android 7 WebView with wrap_content Android 7 WebView with wrap_content google-chrome google-chrome

Android 7 WebView with wrap_content


Workaround is:

waiting while html page will be loaded and run JS inside page to detect content height and set it to WebView Layout Parameters height.

It is easy to run JS inside page, just navigate to url like

javascript:Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight);

To pass the result to Java code you must provide Java-Java Script interface as described here https://developer.android.com/guide/webapps/webview.html (Binding JavaScript code to Android code)

Your url to navigate must looks like

javascript:myfunc(Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight));

The myfunc will be called and you will get the height of page. Now just set in height to WebView height.


Using WebView to showing contents inside a RecyclerView is a little bit risky and it is not so efficient. You have no idea how it works in different devices!

I suggest to change your solution using TextView and converting HTML contents to formatted text using this command

textView.setText(Html.fromHtml(<YOUR HTML CONTENT>))

By the way, These are some efforts I have done with WebView to achieve a fix size for showing some ads banner content:

public class AdsWebView extends WebView {// some setup codes...private static final int MAX_SCALE = 120;public AdsWebView(Context context) {    setVerticalScrollBarEnabled(false);    setHorizontalScrollBarEnabled(false);    setScrollbarFadingEnabled(false);    setupAdsScale();}private int getAdsScale() {    int width = getDisplayWidth(getContext());    Double val = Double.valueOf(width) / Double.valueOf(480);    val = val * 100d;    return val.intValue();}private void setupAdsScale() {    int scale = getAdsScale();    if (scale > MAX_SCALE)        scale = MAX_SCALE;    setInitialScale(scale);}private int getDisplayWidth(Context context) {    try {        Activity activity = (Activity) context;        if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {            Display display = activity.getWindowManager()                    .getDefaultDisplay();            return display.getWidth();        } else {            Display display = activity.getWindowManager()                    .getDefaultDisplay();            Point size = new Point();            display.getSize(size);            return size.x;        }    } catch (Exception e) {        e.printStackTrace();        return 0;    }}