Get screen width and height in Android
How can I get the screen width and height and use this value in:
@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
Log.e(TAG, "onMeasure" + widthSpecId);
setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT -
game.findViewById(R.id.flag).getHeight());
}
Solution 1:
Using this code, you can get the runtime display's width & height:
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
In a view you need to do something like this:
((Activity) getContext()).getWindowManager()
.getDefaultDisplay()
.getMetrics(displayMetrics);
In some scenarios, where devices have a navigation bar, you have to check at runtime:
public boolean showNavigationBar(Resources resources)
{
int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
return id > 0 && resources.getBoolean(id);
}
If the device has a navigation bar, then count its height:
private int getNavigationBarHeight() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int usableHeight = metrics.heightPixels;
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight)
return realHeight - usableHeight;
else
return 0;
}
return 0;
}
So the final height of the device is:
int height = displayMetrics.heightPixels + getNavigationBarHeight();
Solution 2:
There is a very simple answer and without pass context
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
Note: if you want the height include navigation bar, use method below
WindowManager windowManager =
(WindowManager) BaseApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
final Display display = windowManager.getDefaultDisplay();
Point outPoint = new Point();
if (Build.VERSION.SDK_INT >= 19) {
// include navigation bar
display.getRealSize(outPoint);
} else {
// exclude navigation bar
display.getSize(outPoint);
}
if (outPoint.y > outPoint.x) {
mRealSizeHeight = outPoint.y;
mRealSizeWidth = outPoint.x;
} else {
mRealSizeHeight = outPoint.x;
mRealSizeWidth = outPoint.y;
}
Solution 3:
Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}