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()); } 334 Answers
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(); 14There 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; } 6Just 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(); } 4Why not
DisplayMetrics displaymetrics = getResources().getDisplayMetrics();
then use
1displayMetrics.widthPixels (heightPixels)
It’s very easy to get in Android:
int width = Resources.getSystem().getDisplayMetrics().widthPixels; int height = Resources.getSystem().getDisplayMetrics().heightPixels; 1• Kotlin Version via Extension Property
If you want to know the size of the screen in pixels as well as dp, using these extension properties really helps:
DimensionUtils.kt
import android.content.Context import android.content.res.Resources import android.graphics.Rect import android.graphics.RectF import android.os.Build import android.util.DisplayMetrics import android.view.WindowManager import kotlin.math.roundToInt /** * @author aminography */ private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics } /** * Returns boundary of the screen in pixels (px). */ val screenRectPx: Rect get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) } /** * Returns boundary of the screen in density independent pixels (dp). */ val screenRectDp: RectF get() = screenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) } /** * Returns boundary of the physical screen including system decor elements (if any) like navigation * bar in pixels (px). */ val Context.physicalScreenRectPx: Rect get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { (applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager) .run { DisplayMetrics().also { defaultDisplay.getRealMetrics(it) } } .run { Rect(0, 0, widthPixels, heightPixels) } } else screenRectPx /** * Returns boundary of the physical screen including system decor elements (if any) like navigation * bar in density independent pixels (dp). */ val Context.physicalScreenRectDp: RectF get() = physicalScreenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) } /** * Converts any given number from pixels (px) into density independent pixels (dp). */ val Number.px2dp: Float get() = this.toFloat() / displayMetrics.density /** * Converts any given number from density independent pixels (dp) into pixels (px). */ val Number.dp2px: Int get() = (this.toFloat() * displayMetrics.density).roundToInt() Usage:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val widthPx = screenRectPx.width() val heightPx = screenRectPx.height() println("[PX] screen width: $widthPx , height: $heightPx") val widthDp = screenRectDp.width() val heightDp = screenRectDp.height() println("[DP] screen width: $widthDp , height: $heightDp") println() val physicalWidthPx = physicalScreenRectPx.width() val physicalHeightPx = physicalScreenRectPx.height() println("[PX] physical screen width: $physicalWidthPx , height: $physicalHeightPx") val physicalWidthDp = physicalScreenRectDp.width() val physicalHeightDp = physicalScreenRectDp.height() println("[DP] physical screen width: $physicalWidthDp , height: $physicalHeightDp") } } Result:
When the device is in portrait orientation:
[PX] screen width: 1440 , height: 2392 [DP] screen width: 360.0 , height: 598.0 [PX] physical screen width: 1440 , height: 2560 [DP] physical screen width: 360.0 , height: 640.0 When the device is in landscape orientation:
[PX] screen width: 2392 , height: 1440 [DP] screen width: 598.0 , height: 360.0 [PX] physical screen width: 2560 , height: 1440 [DP] physical screen width: 640.0 , height: 360.0 2Try below code :-
1.
Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; 2.
Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); // deprecated int height = display.getHeight(); // deprecated or
int width = getWindowManager().getDefaultDisplay().getWidth(); int height = getWindowManager().getDefaultDisplay().getHeight(); 3.
DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); metrics.heightPixels; metrics.widthPixels; 3You can get width and height from context
java:
int width= context.getResources().getDisplayMetrics().widthPixels; int height= context.getResources().getDisplayMetrics().heightPixels; kotlin
val width: Int = context.resources.displayMetrics.widthPixels val height: Int = context.resources.displayMetrics.heightPixels DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics(); int widthPixels = lDisplayMetrics.widthPixels; int heightPixels = lDisplayMetrics.heightPixels; For kotlin user's
fun Activity.displayMetrics(): DisplayMetrics { val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) return displayMetrics } And in Activity you could use it like
resources.displayMetrics.let { displayMetrics -> val height = displayMetrics.heightPixels val width = displayMetrics.widthPixels } Or in fragment
activity?.displayMetrics()?.run { val height = heightPixels val width = widthPixels } DisplayMetrics dimension = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dimension); int width = dimension.widthPixels; int height = dimension.heightPixels; Get the value of screen width and height.
Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); width = size.x; height = size.y; None of the answers here work correctly for Chrome OS multiple displays, or soon-to-come Foldables.
When looking for the current configuration, always use the configuration from your current activity in
getResources().getConfiguration(). Do not use the configuration from your background activity or the one from the system resource. The background activity does not have a size, and the system's configuration may contain multiple windows with conflicting sizes and orientations, so no usable data can be extracted.
So the answer is
val config = context.getResources().getConfiguration() val (screenWidthPx, screenHeightPx) = config.screenWidthDp.dp to config.screenHeightDp.dp As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.
getWindowManager().
getDefaultDisplay().getMetrics(displayMetrics);
This code given below is in kotlin and is written accodring to the latest version of Android help you determine width and height:
fun getWidth(context: Context): Int { var width:Int = 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val displayMetrics = DisplayMetrics() val display: Display? = context.getDisplay() display!!.getRealMetrics(displayMetrics) return displayMetrics.widthPixels }else{ val displayMetrics = DisplayMetrics() this.windowManager.defaultDisplay.getMetrics(displayMetrics) width = displayMetrics.widthPixels return width } } fun getHeight(context: Context): Int { var height: Int = 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val displayMetrics = DisplayMetrics() val display = context.display display!!.getRealMetrics(displayMetrics) return displayMetrics.heightPixels }else { val displayMetrics = DisplayMetrics() this.windowManager.defaultDisplay.getMetrics(displayMetrics) height = displayMetrics.heightPixels return height } } 2fun Activity.getRealScreenSize(): Pair<Int, Int> { //<width, height> return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val size = Point() display?.getRealSize(size) Pair(size.x, size.y) } else { val size = Point() windowManager.defaultDisplay.getRealSize(size) Pair(size.x, size.y) }} This is an extension function and you can use in your activity in this way:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val pair = getRealScreenSize() pair.first //to get width pair.second //to get height } 2Some methods, applicable for retrieving screen size, are deprecated in API Level 31, including Display.getRealMetrics() and Display.getRealSize(). Starting from API Level 30 we can use WindowManager#getCurrentWindowMetrics(). The clean way to get screen size is to create some Compat class, e.g.:
object ScreenMetricsCompat { private val api: Api = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30() else Api() /** * Returns screen size in pixels. */ fun getScreenSize(context: Context): Size = api.getScreenSize(context) @Suppress("DEPRECATION") private open class Api { open fun getScreenSize(context: Context): Size { val display = context.getSystemService(WindowManager::class.java).defaultDisplay val metrics = if (display != null) { DisplayMetrics().also { display.getRealMetrics(it) } } else { Resources.getSystem().displayMetrics } return Size(metrics.widthPixels, metrics.heightPixels) } } @RequiresApi(Build.VERSION_CODES.R) private class ApiLevel30 : Api() { override fun getScreenSize(context: Context): Size { val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics return Size(metrics.bounds.width(), metrics.bounds.height()) } } } Calling ScreenMetricsCompat.getScreenSize(this).height in Activity we can get a screen height.
Full way to do it, that returns the true resolution:
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Point size = new Point(); wm.getDefaultDisplay().getRealSize(size); final int width = size.x, height = size.y; And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:
/** * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br> * The result should be consistent no matter the orientation of the device */ @JvmStatic fun getScreenNaturalOrientation(context: Context): Int { //based on : val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val config = context.resources.configuration val rotation = windowManager.defaultDisplay.rotation return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT) Configuration.ORIENTATION_LANDSCAPE else Configuration.ORIENTATION_PORTRAIT } /** * returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device */ @JvmStatic fun getScreenNaturalSize(context: Context): Point { val screenNaturalOrientation = getScreenNaturalOrientation(context) val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val point = Point() wm.defaultDisplay.getRealSize(point) val currentOrientation = context.resources.configuration.orientation if (currentOrientation == screenNaturalOrientation) return point else return Point(point.y, point.x) } I use the following code to get the screen dimensions
getWindow().getDecorView().getWidth() getWindow().getDecorView().getHeight() 1As getMetrics and getRealMetrics are deprecated, Google recommends to determine the screen width and height as follows:
WindowMetrics windowMetrics = getActivity().getWindowManager().getMaximumWindowMetrics(); Rect bounds = windowMetrics.getBounds(); int widthPixels = bounds.width(); int heightPixels = bounds.height(); However, I've figured out another methode that gives me the same results:
Configuration configuration = mContext.getResources().getConfiguration(); Display.Mode mode = display.getMode(); int widthPixels = mode.getPhysicalWidth(); int heightPixels = mode.getPhysicalHeight(); 1Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int mWidthScreen = display.getWidth(); int mHeightScreen = display.getHeight(); 1public class DisplayInfo { int screen_height=0, screen_width=0; WindowManager wm; DisplayMetrics displaymetrics; DisplayInfo(Context context) { getdisplayheightWidth(context); } void getdisplayheightWidth(Context context) { wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); displaymetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(displaymetrics); screen_height = displaymetrics.heightPixels; screen_width = displaymetrics.widthPixels; } public int getScreen_height() { return screen_height; } public int getScreen_width() { return screen_width; } } I suggest you create extension functions.
/** * Return the width and height of the screen */ val Context.screenWidth: Int get() = resources.displayMetrics.widthPixels val Context.screenHeight: Int get() = resources.displayMetrics.heightPixels /** * Pixel and Dp Conversion */ val Float.toPx get() = this * Resources.getSystem().displayMetrics.density val Float.toDp get() = this / Resources.getSystem().displayMetrics.density val Int.toPx get() = (this * Resources.getSystem().displayMetrics.density).toInt() val Int.toDp get() = (this / Resources.getSystem().displayMetrics.density).toInt() Methods shown here are deprecated/outdated but this is still working.Require API 13
check it out
Display disp= getWindowManager().getDefaultDisplay(); Point dimensions = new Point(); disp.getSize(size); int width = size.x; int height = size.y; As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.
getWindowManager().
getDefaultDisplay().getMetrics(displayMetrics);
This bowl of code help to determine width and height.
public static int getWidth(Context context) { DisplayMetrics displayMetrics = new DisplayMetrics(); Display display = context.getDisplay(); if (display != null) { display.getRealMetrics(displayMetrics); return displayMetrics.widthPixels; } return -1; } For the Height:
public static int getHeight(Context context) { DisplayMetrics displayMetrics = new DisplayMetrics(); Display display = context.getDisplay(); if (display != null) { display.getRealMetrics(displayMetrics); return displayMetrics.heightPixels; } return -1; } 3Try this code for Kotlin
val display = windowManager.defaultDisplay val size = Point() display.getSize(size) var DEVICE_WIDTH = size.x var DEVICE_HEIGHT = size.y Seems like all these answers fail for my Galaxy M51 with Android 11. After doing some research around I found this code :
WindowMetrics windowmetrics = MainActivity.getWindowManager().getCurrentWindowMetrics(); Rect rect = windowmetrics.getBounds(); int width = rect.right; int height =rect.bottom; shows my true device resolution of 1080x2400, the rest only return 810x1800.
1Just use the function below that returns width and height of the screen size as an array of integers
private int[] getScreenSIze(){ DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int h = displaymetrics.heightPixels; int w = displaymetrics.widthPixels; int[] size={w,h}; return size; } On your onCreate function or button click add the following code to output the screen sizes as shown below
int[] screenSize= getScreenSIze(); int width=screenSize[0]; int height=screenSize[1]; screenSizes.setText("Phone Screen sizes \n\n width = "+width+" \n Height = "+height); I updated answer for Kotlin language!
For Kotlin: You should call Window Manager and get metrics. After that easy way.
val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) var width = displayMetrics.widthPixels var height = displayMetrics.heightPixels How can we use it effectively in independent activity way with Kotlin language?
Here, I created a method in general Kotlin class. You can use it in all activities.
private val T_GET_SCREEN_WIDTH:String = "screen_width" private val T_GET_SCREEN_HEIGHT:String = "screen_height" private fun getDeviceSizes(activity:Activity, whichSize:String):Int{ val displayMetrics = DisplayMetrics() activity.windowManager.defaultDisplay.getMetrics(displayMetrics) return when (whichSize){ T_GET_SCREEN_WIDTH -> displayMetrics.widthPixels T_GET_SCREEN_HEIGHT -> displayMetrics.heightPixels else -> 0 // Error } } 1I found weigan's answer best one in this page, here is how you can use that in Xamarin.Android:
public int GetScreenWidth() { return Resources.System.DisplayMetrics.WidthPixels; } public int GetScreenHeight() { return Resources.System.DisplayMetrics.HeightPixels; } Screen resolution is total no of pixel in screen. Following program will extract the screen resolution of the device. It will print screen width and height. Those values are in pixel.
public static Point getScreenResolution(Context context) { // get window managers WindowManager manager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point point = new Point(); display.getSize(point); // get width and height int width = point.x; int height = point.y; return point; }