我收到错误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)
我一直在阅读这里有几个相同问题的帖子,但他们的解决方案对我的代码不起作用。我试图获得宽度和高度参数,但我无法弄清楚为什么这不起作用。
答案 0 :(得分:0)
问题在于ViewTreeObserver。您正在尝试获取尚未绘制的元素的宽度和高度。
简而言之,onCreate(),onStart()或onResume()中尚未构建视图。由于它们在技术上不存在(就ViewGroup而言),它们的尺寸为0。
很长一段时间,你可以到这里更好地解释如何处理它。
How do you to retrieve dimensions of a view? getHeight() and getWidth() always return zero
我建议你尝试DisplayMetrics来获得高度和宽度..
喜欢this