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?
First get view (eg. by
findViewById()
) and then you can use getWidth() on the view itself.Find width and height of the screen:
Using this, we can get the latest and above SDK 13.
Simplest way:
For dynamically scaling using XML there is an attribute called "android:layout_weight"
The below example, modified from synic's response on this thread, shows a button that takes up 75% of the screen (weight = .25) and a text view taking up the remaining 25% of the screen (weight = .75).
You can do get the height size using :
and the width size using
This is not an answer for the OP, as he wanted the display dimensions in real pixels. I wanted the dimensions in "device-independent-pixels", and putting together answers from here https://stackoverflow.com/a/17880012/253938 and here https://stackoverflow.com/a/6656774/253938 I came up with this: