有没有办法在使用Java加载垂直滚动的网页后获取Android WebView内容的宽度?
class YourCustomWebView extends WebView {
public YourCustomWebView(Context context) {
super(context);
}
public int getContentWidth()
{
return this.computeHorizontalScrollRange();
}
}
public void onPageFinished(WebView page, String url) {
Log.v(LOG_TAG,"ContentWidth: " + ((YourCustomWebView) page).getContentWidth());
}
在加载HTML后,您需要WebView内容的宽度和高度。
是的,您需要,但是没有getContentWidth方法(只有视口值),并且getContentHeight()不准确!
答案:子类化WebView:
/*
Jon Goodwin
*/
package com.example.html2pdf;//your package
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
class CustomWebView extends WebView
{
public int rawContentWidth = 0; //unneeded
public int rawContentHeight = 0; //unneeded
Context mContext = null; //unneeded
public CustomWebView(Context context) //unused constructor
{
super(context);
mContext = this.getContext();
}
public CustomWebView(Context context, AttributeSet attrs) //inflate constructor
{
super(context,attrs);
mContext = context;
}
public int getContentWidth()
{
int ret = super.computeHorizontalScrollRange();//working after load of page
rawContentWidth = ret;
return ret;
}
public int getContentHeight()
{
int ret = super.computeVerticalScrollRange(); //working after load of page
rawContentHeight = ret;
return ret;
}
//=========
}//class
//=========
请检查,http://android.pimmos.com/2011/03/24/how-to-retrieve-the-contentwidth-of-a-webview/
有一个方法webview.getContentHeight();
用于获取内容的高度。没有方法可以获取内容的宽度。您可以使用JavaScript来完成这个操作,并通过JavaScriptInterface从JavaScript中获取它。由于您是从资产文件夹加载的,您可以轻松地添加javascript函数并创建一个JavascriptInterface。