28

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.

4

3 回答 3

71

试试下面你修改过的代码

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

或者

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

基本上你只需要在函数getActivity()之前放置(获取上下文) 。getWindowManager()

于 2012-07-24T11:20:50.447 回答
10

这将为您提供所需的内容,而无需上下文或视图:

import android.content.res.Resources;

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

int height = Resources.getSystem().getDisplayMetrics().heightPixels;
于 2018-12-17T09:43:34.287 回答
4

此代码也适用于片段:

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

比较方向:

if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){...}
于 2018-08-18T21:32:24.167 回答