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

In an Android application, I tried using the following method to get the width and height of the screen:

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

It reports 1080 and 1920 respectively for my phone, which meets the specifications.

However, inside webview, when I used:

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

Shows only 360.

From this I understand that both use a pixel as a unit, so why are the values ​​different?

+6
source share
4 answers

The width of the notifications is the same in both cases, but the units of measurement are different.

eg.

This is in pixels metrics.widthPixels;

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

Convert 360Dps to pixels

In the device xxhdpi 360dps = 1080px

Dp for pixels and vice versa

+5
source

You can use the getResources().getDisplayMetrics() method to get displayMetrics.

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

I use this simple method (inside the 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 to help you.

+1
source

I realized that the dpi of your device belongs to xxhdpi

If 300 dpi can be converted to a width of 1080 pixels. here

and 640 dpi can be converted to 1920 pixels.

also you can enable;

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

Source: https://habr.com/ru/post/1015676/


All Articles