Android 获取WebView的内容宽度高度

本文介绍了如何在Android应用中,通过使用Javascript接口,从WebView获取内容宽度的方法。包括实现步骤、代码示例以及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://www.android100.org/html/201311/19/4804.html

Android开发时,从WebView,我不但想要知道ContentHeight,还想知道ContentWidth。不幸的是,从一个 WebView获取contentWidth是相当困难,因为SDK中没有一个像这样的方法,所以本文为大家呈现了一种实用的解决此问题的方法。


The extensive Android SDK allows you to do many great things with particular views like the WebView for displaying webpages on Android powered devices.
Android SDK 的扩展,通过使用特定的view,允许你做许多事情。比如,WebView,用来在Android手机上展示网页。
 
As of lately while I was experimenting with the Android SDK I was using a WebView in one of my activities.
最近,我在体验Android SDK的时候,在一个Activity中用到了WebView。
From that particular WebView I needed to know the ContentHeight but also the ContentWidth.
从WebView,我不但想要知道ContentHeight,还想知道ContentWidth。
Now getting the contentHeight is easy like so:
现在的情况是:获取contentHeight很easy,如下:

<span style="font-size:18px;">webview.getContentHeight(); </span>

Unfortunately getting the contentWidth from a WebView is rather more difficult, since there is not a simple method like:
不幸的是,从一个WebView获取contentWidth是相当困难,因为SDK中没有一个像这样的方法:

<span style="font-size:18px;">// THIS METHOD DOES NOT EXIST!
    webview.getContentWidth(); </span>

There are ways to get the contentWidth of the rendered HTML page and that is through Javascript. If Javascript can get it for you, then you can also have them in your Java code within your Android App.
当然是有方法获取contentWidth的,就是通过Javascript来获取。如果你能够支持Javascript,那么你就可以在你的 Android 程序中,使用java代码来获取宽度。
By using a JavascriptInterface with your WebView you can let Javascript communicate with your Android App Java code by invoking methods on a registered object that you can embed using the JavascriptInterface.
通过在你的WebView中使用JavascriptInterface,通过调用你注册的JavascriptInterface方法,可以让 Javascript和你的Android程序的java代码相互连通。
So how does this work?
怎么做呢?
For a quick example I created a simple Activity displaying a webview that loads a webpage wich displays a log message and a Toast message with the contentWidth wich was determined using Javascript. Note that this happens AFTER the page was finished loading, because before the page is finished loading the width might not be fully rendered. Also keep in mind that if there is content loaded asynchronously that it doesn't affect widths (most likely only heights will be affected as the width is almost always fully declared in CSS files unless you have a 100% width webpage).
搭建一个快速的例子:创建一个简单的展示webView的Activity,一个LogCat消息,一个Toast消息,用来显示我们通过 Javascript获取的宽度。注意:这些会在网页完全加载之后显示,因为在网页加载完成之前,宽度可能不能够正确的获取到。同时也要注意到,如果是异 步加载,这并不影响宽度(最多高度会受影响,因为宽度总是在CSS文件中做了完全的定义,除非在网页中你用了100%宽度。)。
Below is the code of the Activity Main.java:
下面的代码是Activity的代码:

<span style="font-size:18px;">package com.pimmos.android.samples.webviewcontentwidth;   
import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.widget.Toast;   
public class Main extends Activity {       
    private final static String LOG_TAG = "WebViewContentWidth"; 
    private final Activity activity = this;   
    private static int webviewContentWidth = 0; 
    private static WebView webview;       
  
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
         setContentView(R.layout.main);   
         webview = (WebView) findViewById(R.id.webview); 
         webview.getSettings().setJavaScriptEnabled(true); 
         webview.setSaveEnabled(true); 
         webview.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT"); 
         webview.setWebViewClient(new WebViewClient() { 
            @Override
            public void onPageFinished(WebView view, String url) { 
                 webview.loadUrl("javascript:window.HTMLOUT.getContentWidth(document.getElementsByTagName('html')[0].scrollWidth);"); 
             } 
         }); 
         webview.loadUrl("http://www.pimmos.com/"); 
     } 
  
     class JavaScriptInterface { 
         public void getContentWidth(String value) { 
             if (value != null) { 
                 webviewContentWidth = Integer.parseInt(value); 
                 Log.d(LOG_TAG, "Result from javascript: " + webviewContentWidth); 
                 Toast.makeText(                         activity, 
                         "ContentWidth of webpage is: " + 
                        		 webviewContentWidth                                 + 
                        		 "px", Toast.LENGTH_SHORT).show(); 
             } 
         } 
     } 
} </span>

Below is the XML layout used with the Activity wich only contains a simple WebView:
下面是Activity的Layout,主要就是一个简单的WebView:

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"    
   android:orientation="vertical"
   android:layout_width="fill_parent"    
   android:layout_height="fill_parent"> 
   <WebView android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" /> 
 </LinearLayout> </span>

AndroidManifest.xml layout:
AndroidManifest.xml代码:

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pimmos.android.samples.webviewcontentwidth"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >

        <activity
            android:name=".Main"
            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-sdk android:minSdkVersion="7" />

    <uses-permission android:name="android.permission.INTERNET" />

</manifest></span>


### Android WebView 内容高度留白问题解决方案 在 Android 开发中,WebView 是一个非常常见的组件,用于加载网页或显示 HTML 内容。然而,有时开发者会遇到 WebView 显示内容时出现高度留白的问题,这通常是由以下几个原因引起的[^1]: - **CSS 样式问题**:HTML 或 CSS 中的样式可能导致内容未能正确填充 WebView高度。 - **JavaScript 执行问题**:某些情况下,JavaScript 代码未能正确调整 WebView高度。 - **WebView 设置问题**:WebView 的配置可能未正确设置,例如缩放、视口(viewport)等。 #### 解决方案 ##### 1. 确保正确的 WebView 配置 在使用 WebView 时,需要确保 WebView 的设置是正确的。以下是一个典型的 WebView 配置示例[^2]: ```java WebView webView = findViewById(R.id.webview); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); // 启用 JavaScript webSettings.setUseWideViewPort(true); // 支持 viewport webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕宽度 webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // 滚动条样式 ``` ##### 2. 使用 JavaScript 动态调整 WebView 高度 通过 JavaScript 可以动态调整 WebView内容高度,以避免留白问题。以下是一个示例代码[^3]: ```javascript function adjustWebViewHeight() { document.body.style.height = 'auto'; // 确保内容高度自动调整 var contentHeight = document.body.scrollHeight; // 获取内容高度 window.AndroidInterface.setContentHeight(contentHeight); // 调用 Java 方法 } ``` 在 Java 代码中,可以通过 WebView 的 `addJavascriptInterface` 方法与 JavaScript 进行交互: ```java webView.addJavascriptInterface(new Object() { @JavascriptInterface public void setContentHeight(int height) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) webView.getLayoutParams(); params.height = height; webView.setLayoutParams(params); } }, "AndroidInterface"); ``` ##### 3. 检查 HTML 和 CSS 样式 确保 HTML 和 CSS 样式不会导致内容高度不足。例如,可以检查是否有固定高度或溢出隐藏的样式[^4]: ```css html, body { margin: 0; padding: 0; height: 100%; /* 确保内容高度占满 */ overflow: hidden; /* 避免滚动条影响 */ } ``` ##### 4. 处理 WebView 加载完成后的回调 在 WebView 加载完成后,调用 JavaScript 方法调整高度。可以通过设置 `WebViewClient` 来监听加载完成事件[^5]: ```java webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); webView.loadUrl("javascript:adjustWebViewHeight();"); } }); ``` ### 注意事项 - 如果 WebView 加载的是本地 HTML 文件,请确保文件路径正确,并且文件中的资源(如图片、CSS 文件)能够被正确加载。 - 在 Android 4.4 及以上版本中,推荐使用 `evaluateJavascript` 方法替代 `loadUrl` 来执行 JavaScript[^6]。 ```java if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { webView.evaluateJavascript("javascript:adjustWebViewHeight();", null); } else { webView.loadUrl("javascript:adjustWebViewHeight();"); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值