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!
You can use the window. innerHeight property to get the viewport height, and the window. innerWidth to get its width. let viewportHeight = window.
The width and height can be obtained by calling getWidth() and getHeight().
I've found a way to know the exact height of my activity: if you have a view filling all the available screen behind the title bar and the task bar, just use View. getBottom() to get the real height of that activity.
View is a basic building block of UI (User Interface) in android. A view is a small rectangular box that responds to user inputs. Eg: EditText, Button, CheckBox, etc. ViewGroup is an invisible container of other views (child views) and other ViewGroup.
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)
(copied from my answer to a related question)
I use the following technique - post a runnable from onCreate()
that will be executed when the view has been created:
contentView = findViewById(android.R.id.content); contentView.post(new Runnable() { public void run() { contentHeight = contentView.getHeight(); } });
This code will run on the main UI thread, after onCreate()
has finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With