How to determine the screen width in terms of dp or dip at runtime in Android? How to determine the screen width in terms of dp or dip at runtime in Android? android android

How to determine the screen width in terms of dp or dip at runtime in Android?


Try this

Display display = getWindowManager().getDefaultDisplay();DisplayMetrics outMetrics = new DisplayMetrics ();display.getMetrics(outMetrics);float density  = getResources().getDisplayMetrics().density;float dpHeight = outMetrics.heightPixels / density;float dpWidth  = outMetrics.widthPixels / density;

OR

Thanks @Tomáš Hubálek

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    float dpHeight = displayMetrics.heightPixels / displayMetrics.density;float dpWidth = displayMetrics.widthPixels / displayMetrics.density;


I stumbled upon this question from Google, and later on I found an easy solution valid for API >= 13.

For future references:

Configuration configuration = yourActivity.getResources().getConfiguration();int screenWidthDp = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.

See Configuration class reference

Edit: As noted by Nick Baicoianu, this returns the usable width/height of the screen (which should be the interesting ones in most uses). If you need the actual display dimensions stick to the top answer.


2021 Answer simplified for Kotlin:

val widthDp = resources.displayMetrics.run { widthPixels / density }val heightDp = resources.displayMetrics.run { heightPixels / density }

Or as one-liner:

val (height, width) = resources.displayMetrics.run { heightPixels/density to widthPixels/density }