在onCreate中获取内容视图大小

JMR*_*ies 22 android

我正在寻找一种衡量Android活动实际内容区域尺寸的好方法.

获取显示始终有效.简单地说是这样的:

Display display = getWindowManager().getDefaultDisplay();
Run Code Online (Sandbox Code Playgroud)

您可以获得整个屏幕的像素数.当然,这不会考虑ActionBar,状态栏或任何其他会减少活动本身可用大小的视图.

活动运行后,您可以执行以下操作:

View content = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
Run Code Online (Sandbox Code Playgroud)

仅获取活动内容.但是在onCreate()中执行此操作将导致宽度和高度为0,0的视图.

有没有办法在onCreate期间获得这些维度?我想应该有一种方法可以测量任何状态栏,并从总显示大小中减去,但我无法找到方法.我认为这是唯一的方法,因为内容窗口方法总是在绘制之前返回没有宽度/高度的视图.

谢谢!

kco*_*ock 30

您可以根据目标使用布局或预绘制侦听器.例如,在onCreate()中:

final View content = findViewById(android.R.id.content);
content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //Remove it here unless you want to get this callback for EVERY
        //layout pass, which can get you into infinite loops if you ever
        //modify the layout from within this method.
        content.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        //Now you can get the width and height from content
    }
});
Run Code Online (Sandbox Code Playgroud)

不推荐使用API 16 更新.removeGlobalOnLayoutListener

改成: content.getViewTreeObserver().removeOnGlobalLayoutListener(this)

  • 在API 16+中,你应该使用`removeOnGlobalLayoutListener()`而不是`removeGlobalOnLayoutListener()`.[见这个](http://stackoverflow.com/a/15578844/1074799) (2认同)

Ric*_*ier 19

(从我对相关问题的回答中复制)

我使用以下技术 - onCreate()在创建视图时执行从runnable发布的runnable :

    contentView = findViewById(android.R.id.content);
    contentView.post(new Runnable()
    {
        public void run()
        {
            contentHeight = contentView.getHeight();
        }
    });
Run Code Online (Sandbox Code Playgroud)

完成后,此代码将在主UI线程上运行onCreate().