Get Screen Width and Height in Android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Get Screen Width and Height in Android

Postby vivekkalady » Wed Nov 19, 2014 3:17 pm

There are Different methods in android to get the screen width and height

Display Metrix

Code: Select all

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int height = metrics.heightPixels;
int width = metrics.widthPixels;


If you are in a view you have to use

Code: Select all

((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);‌​

instead of this

getWindowManager().getDefaultDisplay().getMetrics(metrics);



If you are in a fragment,then you can use this

Code: Select all

getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);‌​

instead of this

getWindowManager().getDefaultDisplay().getMetrics(metrics);



Display and Point

Code: Select all

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;



If you are not in an activity

Code: Select all

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;


More Advanced version

Code: Select all

WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
try {
    widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
    heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 17)
try {
    Point realSize = new Point();
    Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
    widthPixels = realSize.x;
    heightPixels = realSize.y;
} catch (Exception ignored) {
}

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron