最后我得到了我的问题的答案。这就是答案。
在加载WebView
之后,我们将在WebViewClient#onPageFinished
中被调用,然后我们需要调用javascript来获取WebView
完整内容的高度。
WebViewClient
类
/**
* Custom web client to perform operations on WebView
*/
class WebClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:AndroidFunction.resize(document.body.scrollHeight)");
}
}
}
之后,我们将在 WebInterface
类中收到一个回调,其中该类已注册为 JavascriptInterface
并提供了高度信息。
/**
* WebView interface to communicate with Javascript
*/
public class WebAppInterface {
@JavascriptInterface
public void resize(final float height) {
float webViewHeight = (height * getResources().getDisplayMetrics().density);
//webViewHeight is the actual height of the WebView in pixels as per device screen density
}
}
WebViewClient.onPageFinished()
只在页面加载完成后调用,因此当内容大小在加载后发生更改时(例如,在页面完成加载后呈现的 Javascript 内容、可展开和可折叠部分的用户交互)该解决方案就会不足。 - trod将您的WebView
放在ScrollView
中,然后webView.getHeight()
将返回实际WebView
内容的高度。请确保您的WebView
的高度属性设置为wrap_content
。
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content">
</WebView>
</ScrollView>
public class CustomWebView extends WebView{
public CustomWebView(Context context) {
super(context);
}
int ContentHeight = 0;
public int getContentHeight(){
if(ContentHeight==0)
ContentHeight = computeVerticalScrollRange();
return ContentHeight;
}
}
Webview拥有一个受保护的方法computeVerticalScrollRange()
。您可以通过创建自定义方法来访问此方法。
((CustomWebView) webView).getContentHeight())
ClassCastException
异常。有什么解决方法吗? - Ivankotlin: myWebView.contentHeight
我的答案:
我认为您需要从layout.xml文件中移除padding属性。
即,从您的XML文件中移除以下内容并尝试。
android:paddingBottom
android:paddingLeft
android:paddingRight
android:paddingTop
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_webview);
}
private int getScale(){
Display display = ((WindowManager)
getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
Double val = new Double(width)/new Double(PIC_WIDTH);
val = val * 100d;
return val.intValue();
}
请查看此 链接以获取更多信息。