获取Android中动态创建的WebView的维度

时间:2011-10-28 20:46:56

标签: android webview size height width

我在android中的webView中嵌入了一个flash媒体播放器,我需要获取webView的尺寸来设置媒体播放器以匹配。如果我在调用中硬编码播放器的像素尺寸,它可以工作,但我希望它根据webView的尺寸进行调整,它使用android:width = fill_parent和android:height = wrap_content,并根据改变而改变屏幕方向。

从我读过的内容,我已经尝试等待onCreate()完成并在onStart()和onResume()方法中调用getHeight()和getWidth(),但它们仍然返回0.这是我在onStart()

中调用的方法
private void playVideo(String path){
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setPluginsEnabled(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    int videoHeight = webView.getHeight();
    int videoWidth = webView.getWidth();
    webView.loadUrl("*my url here*?video="+path+
    ".mp4&width="+videoWidth+"&height="+videoHeight);
}

出于某种原因,我总是得到0作为高度和宽度,无论我是在onCreate(),onStart()还是onResume()中调用方法。我有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

WebView是一个重要的组件,它可能在您尝试获取其宽度和高度之前未在屏幕上完全呈现。

简单的解决方法是将WebView放入另一个容器(最好是FrameLayout)并获取FrameLayout的尺寸。

WebView的维度始终等于Framelayout的维度,只要它是唯一的子级,其宽度和高度都设置为match_parent

答案 1 :(得分:0)

您需要加载组件的宽度高度 WebView 目录 即可。 是的,但是没有 getContentWidth 方法(只有视图端口值), 并且getContentHeight()不准确

答案:子类WebView:

  1. / * Jon Goodwin * / package com.example.html2pdf; //您的包

    import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView;

    类CustomWebView扩展WebView {     public int rawContentWidth = 0; //不需要     public int rawContentHeight = 0; //不需要     上下文mContext = null; //不需要的

    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 //=========