Question

I'm using this:

int wi=getWindowManager().getDefaultDisplay().getWidth();

to get the screen size in pixels. Is there a way to get the screen size in dpi???

I'm doing this to select different layouts base on the screen size.

Was it helpful?

Solution

Is there a way to get the escreen size in dpi???

DisplayMetrics can tell you the screen size in pixels, plus the screen density. From there, you can calculate the screen size in dp.

I'm doing this to select different layouts base on the screen size.

This is automatically handled for you by the resource framework, if you put your layouts in the proper directories (e.g., res/layout-large/, res/layout-sw600dp/).

OTHER TIPS

you must create metric object and do below

 public class LocalUtil extends Application {
private static Context context1;
private static DisplayMetrics  metrics;
public static void setContext(Context context)
{

        context1=context;
        metrics=context1.getResources().getDisplayMetrics();
}
public static float getDensity()
{
    return metrics.density;
}
public static int getScreenWidth()
{
    return metrics.widthPixels;
}
public static int getScreenHeight()
{
    return metrics.heightPixels;
}
public static float getScreenWidthInDpi()
{
    return metrics.widthPixels/metrics.density;
}
public static float getScreenHeightInDpi()
{
    return metrics.heightPixels/metrics.density;
}

and every you want to use this method you can set context with setcontext method and call best method with your purpose like this code this code is oncreateView of main activity:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    LocalUtil.setContext(getApplicationContext());
    LocalUtil.getScreenWidthInDpi();
    //or call  each method you want
  }

The "screen size in dpi" is a meaningless statement. Do you just want to get the DPI of the display?

Secondly, don't do this.

Seriously, stop. Don't do it.

Use the layout folders as they are intended. If you need a different layout for HDPI, put your custom layout in layout-hdpi.

That said, if you just need the density:

DisplayMetrics metrics = new DisplayMetrics();
getWindow().getDisplayMetrics(metrics);
int dpi = metrics.densityDpi;

Here is a way to calculate the width and height of the screen in pixels.

int widthPixels = getWindowManager().getDefaultDisplay().getWidth();
int heightPixels = getWindowManager().getDefaultDisplay().getHeight();

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

int width = (int) (widthPixels - 0.5f)/scale; //width of screen in dpi
int height = (int) (heightPixels - 0.5f)/scale; //height of screen in dpi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top