Android 内容视图宽度和高度

Android 内容视图宽度和高度,android,window,height,width,Android,Window,Height,Width,我使用以下步骤了解我的显示屏上contentview的宽度和高度 ContentViewWidth = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getWidth(); ContentViewHeight = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getHeight(); 但这种方法在onCreate或onResume中不起作用,如果我在onWindowFocusCh

我使用以下步骤了解我的显示屏上contentview的宽度和高度

ContentViewWidth = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getWidth();
ContentViewHeight = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getHeight();
但这种方法在onCreate或onResume中不起作用,如果我在onWindowFocusChanged中使用这些步骤,我会在手机上看到force close错误


请帮助我如何获取显示屏的内容视图。内容视图不包括状态栏和标题栏维度

以下是我在活动中所做的工作,以确定特定视图子项的内容布局,我知道该子项在屏幕上是端到端延伸的(在本例中是网络视图):

首先,从OnGlobalLayoutListener继承:

public class ContainerActivity extends Activity implements ViewTreeObserver.OnGlobalLayoutListener {
...
接下来,实现监听器界面的onGlobalLayout方法(注意,我做了一些像素计算,这些计算与计算中等缩放倾角有关:

@Override
public void onGlobalLayout() {
    int nH = this.mWebView.getHeight();
    int nW = this.mWebView.getWidth();

    if (nH > 0 && nW > 0)
    {
        DisplayMetrics oMetrics = new DisplayMetrics();

        this.getWindowManager().getDefaultDisplay().getMetrics(oMetrics); 

        nH = (nH * DisplayMetrics.DENSITY_DEFAULT) / oMetrics.densityDpi;
        nW = (nW * DisplayMetrics.DENSITY_DEFAULT) / oMetrics.densityDpi;

        // do something with nH and nW                  

        this.mWebView.getViewTreeObserver().removeGlobalOnLayoutListener
            ( this
            );

            ...         
    }
}
最后,确保告诉onCreate()内的视图元素(本例中为mWebView)您正在侦听布局事件:

this.setContentView(this.mWebView = new WebView(this));

this.mWebView.getViewTreeObserver().addOnGlobalLayoutListener
    ( this
    );

这种方法适用于较旧的android版本。我相信ics+为每个可以绑定到的视图都有一个布局侦听器,因此将以类似的方式使用。

我使用以下技术-发布一个可运行的from
onCreate()
,该侦听器将在创建视图时执行:

    contentView = findViewById(android.R.id.content);
    contentView.post(new Runnable()
    {
        public void run()
        {
            contentHeight = contentView.getHeight();
        }
    });
onCreate()
完成后,此代码将在主UI线程上运行


如果您试图获取内容视图本身的高度,则需要从高度中减去填充-这是因为Android 2.x与4.x的视图布局不同

contentHeight = contentView.getHeight() - contentView.getTopPadding();
在创建客户端区域之前,您可能需要使用“无法拥有客户端区域”
Rect rectangle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
int contentHeight = window.findViewById(Window.ID_ANDROID_CONTENT).getHeight();
int contentWidth = window.findViewById(Window.ID_ANDROID_CONTENT).getWidth();