WebView: java.lang.IllegalArgumentException: width and height 必须> 0



我得到错误java.lang.IllegalArgumentException: width and height must be > 0,我认为这个错误可能是由webview引起的。我试图在webview中显示渲染的PDF文件,有一些文件工作正常,但其他文件启动此错误。

activity_convert.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
    android:id="@+id/webView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</LinearLayout>

onCreate方法:

//Setup webview
    wv = (WebView)findViewById(R.id.webView1);
    wv.getSettings().setBuiltInZoomControls(true);//show zoom buttons
    wv.getSettings().setSupportZoom(true);//allow zoom
    //get the width of the webview
    wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            ViewSize = wv.getWidth();
            //ViewSize = wv.getHeight();
            System.out.println("webView: " + wv.getWidth());
            System.out.println("webView: " + wv.getHeight());
            wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    });
PDF呈现:

//create pdf document object from bytes
ByteBuffer bb = ByteBuffer.NEW(data);
PDFFile pdf = new PDFFile(bb);
//Get the first page from the pdf doc
PDFPage PDFpage = pdf.getPage(1, true);
//create a scaling value according to the WebView Width
final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
//convert the page into a bitmap with a scaling value
Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true)

我已经读了几个帖子这里有同样的问题,但他们的解决方案不适合我的代码。我试图得到宽度和高度参数,但我不知道为什么这不起作用

问题在于ViewTreeObserver。您正在尝试获取尚未绘制的元素的宽度和高度。

简而言之,视图还没有在onCreate()、onStart()或onResume()中构建。由于它们在技术上不存在(就ViewGroup而言),因此它们的维度为0。

总而言之,你可以到这里了解如何处理它。

如何检索视图的维度?getHeight()和getWidth()总是返回0

我建议你尝试DisplayMetrics来获得高度和宽度。

这样的

相关内容

最新更新