How to get the screen size of the device?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-28 07:04:41
Lukap

OK FINALLY I found what is my problem

Yes this code works fine but I doesn't return pixels, It returns DIP (Density independent pixels ) which is not the same !

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; //320 dip
int height = dm.heightPixels; //533 dip

What I needed is the REAL pixels and the calculation for them is like this:

int widthPix = (int) Math.ceil(dm.widthPixels * (dm.densityDpi / 160.0));

now the widthPix is 480 !

I found your question and it made me wonder why I'm definitely NOT seeing this effect on any device I am developing on or testing with... getWidth()/getHeight() are returning the exact extents of the useable screen. I suspect others will end up here as well, adding code that causes more confusion and not understanding the root cause.

Turns out this is exactly what happens if you explicitly disable pre-scaling See the second bullet point of this document. (A quick Google search on the term "320x533" turned up lots of other people who've encountered this.) Get rid of your pre-scaling and the discrepancy should go away (getWidth()/getHeight() would then return the actual size, not the scaled size.

Note for tablet devs: getWidth()/getHeight() will not return the raw screen size because the bottom bar (48 pixels or so) isn't part of the area an app can draw to. You'll get the size of everything you can draw to (e.g., 1280x752 rather than the full 1280x800 in landscape mode). Again, no pre-scaling means these values are accurate and exact.

Try using Display class rather than DisplayMetrics.

Display dispOb = getWindowManager().getDefaultDisplay();
String widthAndHeight= dispOb.getWidth()+"X"+dispOb.getHeight();

Disable pre-scaling by adding this line to your manifest file:

<supports-screens android:anyDensity="true" />

Position:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="...."
  android:versionCode="1"
  android:versionName="1.0">

<supports-screens android:anyDensity="true" />

<application android:label="@string/app_name" >
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!