Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

android - Get content view size in onCreate

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);

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

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.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
});

Update as of API 16 removeGlobalOnLayoutListener is deprecated.

Change to: content.getViewTreeObserver().removeOnGlobalLayoutListener(this)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...