Android 获取片段中的屏幕宽度和高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11629675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get screen width and height in a Fragment
提问by pengwang
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.
但是目前我扩展了片段并且我不能使用上面的代码来获取宽度。
回答by rajpara
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();
stageWidth = display.getWidth();
stageHeight = display.getHeigth();
Basically you just required to put getActivity()
(to get the context) before getWindowManager()
function.
基本上你只需要getActivity()
在getWindowManager()
函数之前放置(获取上下文)。
回答by Alex Jolig
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;
回答by devB78
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){...}