getting the screen density programmatically in android?

后端 未结 19 3034
感动是毒
感动是毒 2020-11-22 01:56

How to get the screen density programmatically in android?

I mean: How to find the screen dpi of the current device?

19条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:27

    public static String getDensity(Context context) {
        String r;
        DisplayMetrics metrics = new DisplayMetrics();
    
        if (!(context instanceof Activity)) {
            r = "hdpi";
        } else {
            Activity activity = (Activity) context;
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
            if (metrics.densityDpi <= DisplayMetrics.DENSITY_LOW) {
                r = "ldpi";
            } else if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
                r = "mdpi";
            } else {
                r = "hdpi";
            }
        }
    
        return r;
    }
    

提交回复
热议问题