Get screen width and height in a Fragment

Viewed 40815

If I extend activity in my app I can get width and height:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;

or

Display display = getWindowManager().getDefaultDisplay(); 
stageWidth = display.getWidth();
stageHeight = display.getHeigth();

But at present I extend fragment and I can't use the above code to get the width.

3 Answers

This will give you what you want without needing for context or view:

import android.content.res.Resources;

int width = Resources.getSystem().getDisplayMetrics().widthPixels;

int height = Resources.getSystem().getDisplayMetrics().heightPixels;

This code also works with Fragments:

int width = getResources().getConfiguration().screenWidthDp;
int height = getResources().getConfiguration().screenHeightDp;

For comparing orientation:

if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){...}
Related