I created some custom elements, and I want to programmatically place them to the upper right corner (n
pixels from the top edge and m
pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:
int px = screenWidth - m;
int py = screenHeight - n;
How do I get screenWidth
and screenHeight
in the main Activity?
For who is searching for usable screen dimension without Status Bar and Action Bar (also thanks to Swapnil's answer):
Just adding to Francesco's answer. The other observer that is more apt, if you want to find out the location in window or location in screen is ViewTreeObserver.OnPreDrawListener()
This also can be used to find other attributes of a view that is mostly unknown at onCreate() time e.g. the scrolled position, the scaled position.
There is a non-deprecated way to do this using DisplayMetrics (API 1), that avoids the try/catch messiness:
I would wrap the getSize code like this:
One way is:
It is deprecated, and you should try the following code instead. The first two lines of code gives you the DisplayMetrics objecs. This objects contains the fields like heightPixels,widthPixels.
For accessing the height of the status bar for Android devices, we prefer a programmatic way to get it:
Sample code
The variable
result
gives the height in the pixel.For quick access
For more information about height of
Title bar
,Navigation bar
andContent View
, kindly look on Android Device Screen Sizes.