Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get device raw width and height or actual screen width and height ?

I am trying to get the actual screen width and height of the Nexus 7 running on 4.2.

I am doing some runtime calculations based on device width and height to resize buttons and some UI elements, so it will look proper in all devices. my code was working great in all SDKs 4.1 and below but not working on 4.2.

I am using following code to get width and height.

Code: 1

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
mWidth = displaymetrics.widthPixels;
mHeight = displaymetrics.heightPixels;

Code: 2

Point size = new Point();
WindowManager w = getWindowManager();
w.getDefaultDisplay().getSize(size); 
mWidth = size.x;
mHeight = size.y;

I have also tried with undocumented methods

Code: 3

Display display = getWindowManager().getDefaultDisplay();
Method mGetRawW = Display.class.getMethod("getRawWidth");
Method mGetRawH = Display.class.getMethod("getRawHeight");
mWidth = (Integer) mGetRawW.invoke(display);
mHeight = (Integer) mGetRawH.invoke(display);

But none of above is working with Nexus 7 running on 4.2, its always subtracting status bar height, I am not getting full height.

I have used some methods to calculate status bat height but not getting proper values,

int statusBarHeight = Math.ceil(25 * context.getResources().getDisplayMetrics().density);

AND

Rect rectgle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight= rectgle.top;

Is there any standard way to get actual device screen height and width?

like image 267
Mac Avatar asked Nov 03 '22 10:11

Mac


1 Answers

Give it a try with the last changes of API 17 :

http://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)

public void getRealSize (Point outSize)
Gets the real size of the display without subtracting any window decor or applying any compatibility scale factors.

If this does'nt work, you can try :

http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics)

like image 135
chip Avatar answered Nov 08 '22 06:11

chip