paradite
paradite

Reputation: 6436

Different width and height from DisplayMetrics and $(window).width() in WebView

Inside an Android app, I tried using the following way to obtain the screen width and height:

DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final int screenWidth = metrics.widthPixels;
        final int screenHeight = metrics.heightPixels;

This reports 1080 and 1920 respectively for my phone, which matches the specs.

However, inside a webview, when I used:

var screenWidth = $(window).width();

This reports only 360.

From this what I understand, both are using pixel as unit, so why are the values different?

Upvotes: 7

Views: 879

Answers (4)

Manoj Perumarath
Manoj Perumarath

Reputation: 10254

I figured out that the dpi of your device belongs to xxhdpi

Where 300 dpi can be converted as 1080 pixels width. here

and 640 dpi can be converted as 1920 pixels.

also you can include;

 private int convertDpToPixel(int dp) {
    Resources r = getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, 
r.getDisplayMetrics());
    return (int) px;
}

Upvotes: 1

PEHLAJ
PEHLAJ

Reputation: 10136

Notice width is same in both cases but units are different.

E.g.

This is in Pixels metrics.widthPixels;

This one is in Dps 360 OR $(window).width();

Convert 360Dps to pixels

On xxhdpi device, 360dps = 1080px

Dp to pixels & vice versa

Upvotes: 5

mcatta
mcatta

Reputation: 491

I use this simple method (inside a utils class) to convert px <-> dp.

public static int convertIntToDp(int inputValue, DisplayMetrics displayMetrics){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, inputValue, displayMetrics);
    }

I hope help you

Upvotes: 1

Chetan Joshi
Chetan Joshi

Reputation: 5721

You can use getResources().getDisplayMetrics() method to obtain displayMetrics .

DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 
final int screenWidth = metrics.widthPixels;
final int screenHeight = metrics.heightPixels;

Upvotes: 1

Related Questions