1

I need to create a webview that I need to set a fixed size.

Say the webview should have a pixel width of 570, but the device only has a 320px width.

How do I render the webview size that is irrelevant to the parents size?

final WebView webView = new WebView(context);
webView.loadDataWithBaseURL("", html, "text/html", "utf-8", null);

webView.setDrawingCacheEnabled(true);
webView.setVisibility(View.INVISIBLE);
rootView.addView(webView);

webView.setWebViewClient(new CustomtWebClient(context));

In the CustomtWebClient

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    final WebView webView = view;
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(),
                    webView.getContentHeight() * (int) webView.getScale(), Bitmap.Config.ARGB_8888);
            final Canvas c = new Canvas(bitmap);
            webView.draw(c);

            //additional stuff...

        }
    }, 100);
}

As you can see the webview should only be rendered and then turned into a bitmap.

But the way I do it now the webview is restricted to the parents size, which is based on the device.

I need an independent webview.

Joakim Engstrom
  • 6,243
  • 12
  • 48
  • 67

1 Answers1

2

You should be able to have an 'off screen' WebView without attaching it to the view hierarchy (that is without calling rootView.addView):

final WebView webView = new WebView(context);
webView.loadDataWithBaseURL("", html, "text/html", "utf-8", null);

webView.layout(0, 0, desiredWidth, desiredHeight);
webView.setWebViewClient(new CustomtWebClient(context));

Unfortunately you approach of using onPageFinished will not work reliably - it's too early and you'll sometimes (or on some devices) get a white page. Currently the WebView doesn't have a good callback for knowing when it has "something good to draw".

The best you could do is probably a combination of the deprecated setPictureListener and an arbitrary timeout (say 100ms). Alternatively you could render to a small bitmap first and check if it's completely white.

marcin.kosiba
  • 3,221
  • 14
  • 19
  • I was unable to create 'off screen' WebView. webView.draw(c) draw black. But if set webView.setVisibility(View.INVISIBLE) all work fine – ArkadiBernov Mar 13 '20 at 07:49