Is there a way to get screen size in dpi

ぃ、小莉子 提交于 2019-12-24 05:29:14

问题


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.


回答1:


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/).




回答2:


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
  }



回答3:


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;



回答4:


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


来源:https://stackoverflow.com/questions/15213270/is-there-a-way-to-get-screen-size-in-dpi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!