Skip to content Skip to sidebar Skip to footer

How To Get Device Height And Width At Runtime?

I am developing an app in which I have to make our app to fit for every device - for both tablet and android mobiles. Now I want to get the device height and width at runtime and i

Solution 1:

DisplaymDisplay= activity.getWindowManager().getDefaultDisplay();
finalintwidth= mDisplay.getWidth();
finalintheight= mDisplay.getHeight();

This way you can get the screen size.

Since this API is depricated in the new SDK versions you can use this.

DisplayMetricsdisplayMetrics= context.getResources().getDisplayMetrics();
intwidth= displayMetrics.widthPixels;
intheight= displayMetrics.heightPixels;

Solution 2:

In a Activity scope do:

DisplayMetricsdm=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
intw= dm.widthPixels; // etc...

Solution 3:

In the onCreate of your activity you can do

mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();mScreenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();

and later use these variables to access device height and width

Solution 4:

this is how you get the available screen dimensions. This will get you not the raw pixel size but the available space of your window/activity.

PointoutSize=newPoint();
    getWindowManager().getDefaultDisplay().getSize(outSize);

Also you can have different layout xml files for both landscape and portrait. Put your xml for portrait in res/layout-port. Layout for landscape can be put into res/layout-land. You should read up how android handles resources

Solution 5:

You can get all the display related information using the class Display Metrics http://developer.android.com/reference/android/util/DisplayMetrics.html

you would require

DisplayMetricsmetrics=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

After this all the required information will be present in your metrics object.

The other option is to call

getActivity().getWindowManager().getDefaultDisplay().getWidth()
getActivity().getWindowManager().getDefaultDisplay().getHeight()

Post a Comment for "How To Get Device Height And Width At Runtime?"