Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get screen width and height

I tried to use following code to get screen width and height in android app development:

Display display = getWindowManager().getDefaultDisplay();  int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); 

but I got NullPointerException for my display, why? how to get screen width and height then?

like image 209
Leem Avatar asked Jun 29 '11 12:06

Leem


2 Answers

If you're calling this outside of an Activity, you'll need to pass the context in (or get it through some other call). Then use that to get your display metrics:

DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int width = metrics.widthPixels; int height = metrics.heightPixels; 

UPDATE: With API level 17+, you can use getRealSize:

Point displaySize = new Point(); activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize); 

If you want the available window size, you can use getDecorView to calculate the available area by subtracting the decor view size from the real display size:

Point displaySize = new Point(); activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);  Rect windowSize = new Rect(); ctivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(windowSize);  int width = displaySize.x - Math.abs(windowSize.width()); int height = displaySize.y - Math.abs(windowSize.height()); return new Point(width, height); 

getRealMetrics may also work (requires API level 17+), but I haven't tried it yet:

DisplayMetrics metrics = new DisplayMetrics(); activity.GetWindowManager().getDefaultDisplay().getRealMetrics(metrics); 
like image 146
areyling Avatar answered Sep 24 '22 10:09

areyling


Within an activity, you can call:

int width = this.getResources().getDisplayMetrics().widthPixels; int height = this.getResources().getDisplayMetrics().heightPixels; 

When you're in a View, then you need to get the Context first:

int width = getContext().getResources().getDisplayMetrics().widthPixels; int height = getContext().getResources().getDisplayMetrics().heightPixels; 

This will work in all Android version, available since API 1, and never deprecated.

like image 45
Khulja Sim Sim Avatar answered Sep 24 '22 10:09

Khulja Sim Sim