在页面加载后,获取Android WebView垂直滚动后的内容宽度

5
有没有办法在使用Java加载垂直滚动的网页后获取Android WebView内容的宽度?

内容宽度是什么意思?是指Web视图的宽度吗? - Aman Gautam
我的意思是我想知道显示HTML页面的高度和宽度,而不是Web视图的高度/宽度。谢谢 - Ramanan
您是否拥有要在Webview中加载的页面?也就是说,您能否修改该页面? - Aman Gautam
你看过这个链接吗?http://android.pimmos.com/2011/03/24/how-to-retrieve-the-contentwidth-of-a-webview/ - Aman Gautam
是的,我从资产中加载了我的HTML文件。感谢上面的链接。 - Ramanan
3个回答

7
如果您有扩展使用的WebView的选项,您也可以尝试受保护的Method computeHorizontalScrollRange()的输出。
更新:我忘记提到,只有在内容大于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());
}

computeHorizontalScrollRange() 对我来说总是返回零。还有其他的解决方法吗? - airowe

4

在加载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
//=========

0

请检查,http://android.pimmos.com/2011/03/24/how-to-retrieve-the-contentwidth-of-a-webview/

有一个方法webview.getContentHeight();用于获取内容的高度。没有方法可以获取内容的宽度。您可以使用JavaScript来完成这个操作,并通过JavaScriptInterface从JavaScript中获取它。由于您是从资产文件夹加载的,您可以轻松地添加javascript函数并创建一个JavascriptInterface。


2
如果有人想查看这个失效链接中的内容:http://web.archive.org/web/20140218103526/http://android.pimmos.com/2011/03/24/how-to-retrieve-the-contentwidth-of-a-webview - airowe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接