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:

Display mDisplay = activity.getWindowManager().getDefaultDisplay();
final int width  = mDisplay.getWidth();
final int height = mDisplay.getHeight();

This way you can get the screen size.

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

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;

Solution 2:

In a Activity scope do:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int w = 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.

    Point outSize = new Point();
    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

DisplayMetrics metrics = new DisplayMetrics();
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?"