Home > DeveloperSection > Forums > How to get screen dimensions in pixels
Samuel Fernandes
Samuel Fernandes

Total Post:156

Points:1096
Posted on    April-23-2015 5:19 AM

 Android Android  Android Layout 
Ratings:


 1 Reply(s)
 453  View(s)
Rate this:
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?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    April-23-2015 8:05 AM

if you want the display dimensions in pixels you can use getSize:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
If you're not in an Activity you can get the default Display via WINDOW_SERVICE:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Before getSize was introduced (in API level 13), you could use the getWidth and getHeight methods that are now deprecated:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated
For the use case you're describing however, a margin/padding in the layout seems more appropriate.

Don't want to miss updates? Please click the below button!

Follow MindStick