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()); }
Display display = getWindowManager(). getDefaultDisplay(); Point size = new Point(); display. getSize(size); int width = size. x; int height = size.
Screen size measurements for smartphones are calculated by measuring diagonally from the upper left-hand corner of the screen to the lower right-hand corner*. These measurements are expressed in inches.
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();
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With