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 what I understand, both are using pixel as unit, so why are the values different?
4 Answers
Answers 1
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
Answers 2
You can use getResources().getDisplayMetrics()
method to obtain displayMetrics .
DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); final int screenWidth = metrics.widthPixels; final int screenHeight = metrics.heightPixels;
Answers 3
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
Answers 4
I figured out that the dpi of your device belongs to xxhdpi
Where 300 dpi can be converted as 1080 pixels width.
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; }
0 comments:
Post a Comment