获取的onCreate内容视图大小 [英] Get content view size in onCreate

查看:93
本文介绍了获取的onCreate内容视图大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找测量实际内容区域的尺寸在Android中的活动的一种好方法。

I'm looking for a good way to measure the dimensions of the actual content area for an activity in Android.

获取显示器始终工作。只要是这样的:

Getting display always works. Simply go like this:

Display display = getWindowManager().getDefaultDisplay();

和你可以得到整个屏幕的像素数。当然,这并没有考虑到动作条,状态栏,或者其他任何意见,这将降低活动本身的可用大小。

And you can get the pixel count for the entire screen. Of course this does not take into consideration the ActionBar, status bar, or any other views which will reduce the available size of the activity itself.

在活动运行时,你可以这样做:

Once the activity is running, you can do this:

View content = getWindow().findViewById(Window.ID_ANDROID_CONTENT);

要只得到了活动内容。但在的onCreate()这样做将导致与宽度和高度0,0的图。

To get the activity content only. But doing this in onCreate() will result in a view with width and height of 0, 0.

有没有办法的onCreate期间得到这些尺寸是多少?我想应该有一种方式来获得的任何状态栏的测量,只是减去从总的显示尺寸,但是我无法找到一个方法来做到这一点。我认为这将是唯一的方法,因为它是之前绘制的内容窗口方法总是返回一个观点,没有宽/高。

Is there a way to get these dimensions during onCreate? I imagine there ought to be a way to get the measurements of any status bars and just subtract that from the total display size, but I'm unable to find a way to do that. I think this would be the only way, because the content window method will always return a view with no width/height before it is drawn.

谢谢!

推荐答案

您可以使用一个布局或pre-平局监听器这一点,这取决于你的目标。例如,在的onCreate():

You can use a layout or pre-draw listener for this, depending on your goals. For example, in 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
    }
});

这篇关于获取的onCreate内容视图大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆