getting the screen density programmatically in android?

后端 未结 19 2659
感动是毒
感动是毒 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条回答
  •  情深已故
    2020-11-22 02:41

    Here are some density constants, source:

    There are, in addition to the standard densities, 5 Intermediate ones. Taking into account this fact, the following code will be a complete working example:

    float density = getResources().getDisplayMetrics().density;
    
    if (density == 0.75f)
    {
        // LDPI
    }
    else if (density >= 1.0f && density < 1.5f)
    {
        // MDPI
    }
    else if (density == 1.5f)
    {
        // HDPI
    }
    else if (density > 1.5f && density <= 2.0f)
    {
        // XHDPI
    }
    else if (density > 2.0f && density <= 3.0f)
    {
        // XXHDPI
    }
    else
    {
        // XXXHDPI 
    }
    

    Alternatively, you can find density constants using the densityDpi:

    int densityDpi = getResources().getDisplayMetrics().densityDpi;
    
    switch (densityDpi)
    {
        case DisplayMetrics.DENSITY_LOW:
            // LDPI
            break;
    
        case DisplayMetrics.DENSITY_MEDIUM:
            // MDPI
            break;
    
        case DisplayMetrics.DENSITY_TV:
        case DisplayMetrics.DENSITY_HIGH:
            // HDPI
            break;
    
        case DisplayMetrics.DENSITY_XHIGH:
        case DisplayMetrics.DENSITY_280:
            // XHDPI
            break;
    
        case DisplayMetrics.DENSITY_XXHIGH:
        case DisplayMetrics.DENSITY_360:
        case DisplayMetrics.DENSITY_400:
        case DisplayMetrics.DENSITY_420:
            // XXHDPI
            break;
    
        case DisplayMetrics.DENSITY_XXXHIGH:
        case DisplayMetrics.DENSITY_560:
            // XXXHDPI
            break;
    }
    

提交回复
热议问题