【问题标题】:Getting the dimensions of a dynamically-created WebView in Android在 Android 中获取动态创建的 WebView 的尺寸
【发布时间】:2011-12-17 14:20:02
【问题描述】:

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

根据我的阅读,我尝试等待 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);
}

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

【问题讨论】:

    标签: android webview size height width


    【解决方案1】:

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

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

    WebView 的尺寸总是等于 Framelayout 的尺寸,只要它是唯一的孩子并且它的宽度和高度都设置为 match_parent

    【讨论】:

    • 我试过了。我使用了:int videoHeight = ((FrameLayout) webView.getParent()).getHeight(); int videoWidth = ((FrameLayout) webView.getParent()).getWidth();,但我仍然得到两个维度的 0。
    【解决方案2】:

    你需要宽度高度的WebView CONTENTS之后你加载你的组件。 是的,但是没有 getContentWidth 方法(只有一个视口值), 并且 getContentHeight() 不准确

    答案:子类WebView:

    1. /* 乔恩·古德温 */ package com.example.html2pdf;//你的包

      导入 android.content.Context;导入android.util.AttributeSet; 导入android.webkit.WebView;

      类 CustomWebView 扩展 WebView { 公共 int rawContentWidth = 0; //不需要 公共 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 //=========
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2014-05-19
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      相关资源
      最近更新 更多