getting the screen density programmatically in android?

后端 未结 19 3052
感动是毒
感动是毒 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
    2020-11-22 02:37

    Try this...

    In kotlin

    fun determineScreenDensityCode(): String {
          return when (resources.displayMetrics.densityDpi) {
             DisplayMetrics.DENSITY_LOW -> "ldpi"
             DisplayMetrics.DENSITY_MEDIUM -> "mdpi"
             DisplayMetrics.DENSITY_HIGH -> "hdpi"
             DisplayMetrics.DENSITY_XHIGH, DisplayMetrics.DENSITY_280 -> "xhdpi"
             DisplayMetrics.DENSITY_XXHIGH, DisplayMetrics.DENSITY_360, DisplayMetrics.DENSITY_400, DisplayMetrics.DENSITY_420 -> "xxhdpi"
             DisplayMetrics.DENSITY_XXXHIGH, DisplayMetrics.DENSITY_560 -> "xxxhdpi"
             else -> "Unknown code ${resources.displayMetrics.densityDpi}"
         }
    }
    

    You can call by println("density: ${determineScreenDensityCode()}") and the output will be System.out: density: xxxhdpi

提交回复
热议问题