pengwang
pengwang

Reputation: 19956

Get screen width and height in a Fragment

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.

Upvotes: 30

Views: 43493

Answers (3)

rajpara
rajpara

Reputation: 5203

Try below modifed code of yours

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

or

Display display = getActivity().getWindowManager().getDefaultDisplay(); 
int stageWidth = display.getWidth();
int stageHeight = display.getHeight();

Basically you just required to put getActivity() (to get the context) before getWindowManager() function.

Upvotes: 74

Ghasem
Ghasem

Reputation: 15573

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;

Upvotes: 11

devB78
devB78

Reputation: 12244

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){...}

Upvotes: 6

Related Questions