乐闻世界logo
搜索文章和话题

How to get the full height of in android WebView?

1个答案

1

In Android, to obtain the full height of a WebView, you must wait for the WebView to finish loading its content before retrieving it based on the actual measured height of the content. The following outlines basic steps and an example demonstrating how to obtain the full height of a WebView in Android:

  1. Call the getContentHeight() method of WebView: This method returns an integer value based on the minimum display unit of the WebView. You need to multiply this value by getScale() (if API level is below 19) or directly use getResources().getDisplayMetrics().density to convert it to pixel units.

  2. Use WebViewClient and WebChromeClient to monitor content loading completion: You need to ensure the page has fully loaded, so monitor the page loading state.

  3. Asynchronously obtain the height: Since WebView content loading is asynchronous, you typically obtain the height after the page has finished loading using the onPageFinished method of WebViewClient or the onProgressChanged method of WebChromeClient.

Example code follows:

java
WebView webView = findViewById(R.id.webview); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Wait for the page to finish loading before retrieving the height webView.post(new Runnable() { @Override public void run() { // Retrieve the actual height of the content int webViewHeight = (int) (webView.getContentHeight() * getResources().getDisplayMetrics().density); // You can perform further operations here, such as setting WebView's LayoutParams } }); } }); // Set WebView properties and load the webpage webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("http://www.example.com");

In this example, we first set up WebViewClient and override the onPageFinished method. After the page has finished loading, we asynchronously retrieve the WebView's content height and convert it from the WebView's minimum unit to pixel units. This is a simple way to obtain the full height of a WebView. However, in actual development, you may need to handle more edge cases, such as pages dynamically loading content or JavaScript execution causing height changes.

2024年6月29日 12:07 回复

你的答案