webView.getMeasuredWidth()和getMeasuredHeight()在4.4.X之前不适用于API

时间:2014-10-16 11:05:11

标签: android webview

我有我的WebView代码

public static void loadHtml (final Context ctx) {

    final WebView webView = new WebView(ctx);

    //runnable and 2s delay is set because i load some javascript in onPageFinished
    //i omitted it for semplicity
    final Handler mHandler = new Handler();

    webView.setWebViewClient(new WebViewClient(){

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            //call some javascript in webView ...

            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {

                    webView.measure(MeasureSpec.makeMeasureSpec(
                            MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                    webView.setDrawingCacheEnabled(true);
                    webView.buildDrawingCache();

                    //take webview screenshot loaded with a pdf/html
                    takeScreenShot(ctx, webView);

                }

            }, 2000);
    }

    webView.loadUrl("file:///android_asset/" + folder + "/index.html");

}


public static void takeScreenShot(Context ctx, WebView webView){

    Bitmap bm = Bitmap.createBitmap(webView.getMeasuredWidth(), //<-- WHERE IT BREAKS
            webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas bigcanvas = new Canvas(bm);
    Paint paint = new Paint();
    int iHeight = bm.getHeight();

    bigcanvas.drawBitmap(bm, 0, iHeight, paint);
    webView.draw(bigcanvas);

    if (bm != null) {
        try {
            OutputStream fOut = null;
            fOut = new FileOutputStream(imageTemp);
            bm.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
            fOut.flush();
            fOut.close();
            bm.recycle();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

当我在带有Android 4.4.2的三星Galaxy标签10.1上运行此代码时,一切正常,但是当我在带有Android 4.2.1的Asus Transformer中运行它时webView.getMeasuredWidth()和webView.getMeasuredHeight()返回0抛出异常:&#34;宽度和高度必须> 0&#34;

我在SO上阅读了很多关于这个问题的话题,但我尝试过的每一个都没有解决我的问题。我也想向API 17客户提供我的应用程序,而不仅仅是从19 ...

开始

有人有解决方案吗?谢谢:))

1 个答案:

答案 0 :(得分:0)

似乎没有WebView低于4.4.X的解决方案

唯一对我有用的是在XML布局中放置一个隐藏的WebView,在loadHtml方法中我检查Android版本

示例代码:

final WebView webView;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    webView = new WebView(ctx);
else {
    webView = (WebView)findViewById(R.id.hidden_webview);
    webView.setVisibility(View.VISIBLE);
}

在第二种情况下,我从内部运行方法中删除此代码

webView.measure(MeasureSpec.makeMeasureSpec(
                        MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();

希望可以帮助别人,抱歉迟到的回答