0

On mdpi device I would like to call this method:

final float scale = getResources().getDisplayMetrics().density;
double height_px =  45 * scale + 0.5;

but I want to ignore the method when the app is run on hdpi devices, how am I able to determine the screen size on my class?

hectichavana
  • 1,436
  • 13
  • 41
  • 71
  • (1) What method - I don't see any? (2) You are already retrieving the density - so just check what it is: http://developer.android.com/guide/practices/screens_support.html – Aleks G May 10 '12 at 14:58
  • yes I dont wrap it on a method. I just wanna know, how am I able to do for example: if the screen size is 320dp then double height_px = 45 * scale + 0.5; how am I able to declare it?? – hectichavana May 10 '12 at 15:03
  • But you already have screen density, screen height and screen width - so what's the problem? – Aleks G May 10 '12 at 15:10
  • Perhaps what you really want is a [dimension resource](http://developer.android.com/guide/topics/resources/more-resources.html#Dimension). If you specify a value in DP then it will automatically adjust depending on your density. – dmon May 10 '12 at 15:27

2 Answers2

7

Yeah simply you can check for scale value like this,

final float scale = getResources().getDisplayMetrics().density;

And now you have scale value. The scale value varies like this,

For MDPI devices, scale value is 1.0.

For LDPI devices, scale value is 0.75.

For HDPI devices, scale value is 1.50.

For XHDPI devices, scale value is 2.0.

Just make a cross check,

if(scale <1.50)
{
double height_px =  45 * scale + 0.5;
}

Which means this code will not be executed for High and above resolutions.

Andro Selva
  • 53,910
  • 52
  • 193
  • 240
6

It's also possible to do sth like this:

int dpiDensity = getResources().getDisplayMetrics().densityDpi;

And then you can compare resulting value with constants from DisplayMetrics like this:

switch(dpiDensity){
    case DisplayMetrics.DENSITY_LOW:
        //Do sth for LDPI-screen devices
        break;
    case DisplayMetrics.DENSITY_MEDIUM:
        //Do sth for MDPI-screen devices
        break;
    case DisplayMetrics.DENSITY_HIGH:
        //Do sth for HDPI-screen devices
        break;
    case DisplayMetrics.DENSITY_XHIGH:
        //Do sth for XHDPI-screen devices
        break;  
}

there is also constant called DENSITY_DEFAULT but its value is same as DENSITY_MEDIUM.

fgeorgiew
  • 1,194
  • 2
  • 8
  • 25