htmlandroidimageandroid-webviewresolution-independence

Different images for different resolutions in HTML resources in Android


How do you display different images for different screen resolutions (hdpi, ldpi, mdpi) in an embedded HTML resource of an Android app?

The HTML resource is located in assets, but can be changed if necessary.

If this is not possible, how do you change the display size of the image based on the screen resolution?


Solution

  • I managed to do this with @media queries and -webkit-device-pixel-ratio. While the images have to be located in assets, you can use folders to organize them properly.

    @media screen and (-webkit-device-pixel-ratio:0.75) {
        #header {
            background-image: url('ldpi/background.png');
            width: 75px;
            height: 75px;
        }
    }
    
    @media screen and (-webkit-device-pixel-ratio:1.0) {
        #header {
            background-image: url('mdpi/background.png');
            width: 100px;
            height: 100px;
        }
    }
    
    @media screen and (-webkit-device-pixel-ratio:1.5) {
        #header {
            background-image: url('hdpi/background.png');
            width: 150px;
            height: 150px;
        }
    }
    

    According to the documentation (Building web pages to support different screen densities), this only works in Android 2.0 or higher.

    You never know enough CSS, it seems.