Search code examples
androidjsonimageviewandroid-screen-supportandroid-screen

android display images (different screen resolutions) on ImageView from json data


I am getting json data. In that json I have a array of images urls for different screen resolutions for one image like this

"images": {
                "full_url": "http://******/assets/tmp/",
                "ldpi": "http://******/assets/tmp/ldpi/****.png",
                "mdpi": "http://******/assets/tmp/mdpi/****.png",
                "hdpi": "http://******/assets/tmp/hdpi/****.png",
                "xdpi": "http://******/assets/tmp/xdpi/****.png"
            }

i want to display this image dependent on screen size


Solution

  • You can use like below,

    float density = getResources().getDisplayMetrics().densityDpi;
    
    //DisplayMetrics.DENSITY_LOW - LDPI(120)
    //DisplayMetrics.DENSITY_MEDIUM - MDPI(160)
    //DisplayMetrics.DENSITY_HIGH - HDPI(240)
    //DisplayMetrics.DENSITY_XHIGH - XHDPI(320)
    //DisplayMetrics.DENSITY_XXHIGH - XXHDPI(480)
    //DisplayMetrics.DENSITY_XXXHIGH - XXXHDPI(640)
    

    based on the density you can add the image, ref this too.

    Ex ;

    if(density == DisplayMetrics.DENSITY_MEDIUM) {
        // Use mdpi image in your JSON
    } else if(density == DisplayMetrics.DENSITY_XHIGH) {
        // use xdpi image in your JSON
    } else if(density == DisplayMetrics.DENSITY_HIGH) {
        // use xdpi image in your JSON
    } else {
        // use full image
    }