Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to code the layout of the android widgets using dip/dp (in java files). At runtime if I code,

int pixel=this.getWindowManager().getDefaultDisplay().getWidth();

this return the screen width in pixels (px). To convert this to dp, I coded:

int dp =pixel/(int)getResources().getDisplayMetrics().density ;

This does not seem to be returning correct answer. I made the emulator of WVGA800 whose screen resolution is 480 by 800. When the run the emulator and let the code print the values of pixel and dp, it came to 320 in both. This emulator is 240 dpi whose scale factor would be 0.75.

like image 990
Khushboo Avatar asked Oct 12 '22 10:10

Khushboo


People also ask

What is the width of Android screen in dp?

Typical numbers for screen width dp are: 320: a phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).

What is dp width?

dp or dip (Density-independent Pixels) Refers to the actual pixels on the screen. Depending on the actual size of the screen in inches. Determined by the actual size of the screen. Based on the actual size of the screen, 1/72 of an inch, assuming a screen with a resolution of 72dpi.


1 Answers

As @Tomáš Hubálek mentioned;
Try something like:

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

OR

Try old answer:

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;
like image 406
Dax Avatar answered Oct 17 '22 05:10

Dax