如何获取WebView的内容宽度[翻译]

原文网址:http://android.pimmos.com/2011/03/24/how-to-retrieve-the-contentwidth-of-a-webview/ javascript

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手机上展现网页。html


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。java


From that particular WebView I needed to know the ContentHeight but also the ContentWidth.
从WebView,我不但想要知道ContentHeight,还想知道ContentWidth。android


Now getting the contentHeight is easy like so:
如今的状况是:获取contentHeight很easy,以下:
web

webview.getContentHeight();


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

// THIS METHOD DOES NOT EXIST!
webview.getContentWidth();

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代码来获取宽度。less


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%宽度。)。async

Below is the code of the Activity Main.java:
下面的代码是Activity的代码:ide


Main.java

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();
             }
         }
     }
}


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

<?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>


AndroidManifest.xml layout:
AndroidManifest.xml代码:

<?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>


You can also download the full source of Android Application - WebViewContentWidth!
你也能够到这里下载所有的源代码 -  WebViewContentWidth!

相关文章
相关标签/搜索