如何在Android中以像素为单位获取屏幕尺寸
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1016896/
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
How to get screen dimensions as pixels in Android
提问by Niko Gamulin
I created some custom elements, and I want to programmatically place them to the upper right corner (n
pixels from the top edge and m
pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:
我创建了一些自定义元素,我想以编程方式将它们放置在右上角(n
来自顶部边缘的m
像素和来自右边缘的像素)。因此我需要获取屏幕宽度和屏幕高度,然后设置位置:
int px = screenWidth - m;
int py = screenHeight - n;
How do I get screenWidth
and screenHeight
in the main Activity?
我如何进入screenWidth
和screenHeight
进入主活动?
回答by Josef Pfleger
If you want the display dimensions in pixels you can use getSize
:
如果您想要以像素为单位的显示尺寸,您可以使用getSize
:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
If you're not in an Activity
you can get the default Display
via WINDOW_SERVICE
:
如果您不在,则Activity
可以Display
通过WINDOW_SERVICE
以下方式获得默认值:
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).
如果您在片段中并想要完成此操作,只需使用 Activity.WindowManager(在 Xamarin.Android 中)或 getActivity().getWindowManager()(在 Java 中)。
Before getSize
was introduced (in API level 13), you could use the getWidth
and getHeight
methods that are now deprecated:
在getSize
引入之前(在 API 级别 13),您可以使用现在已弃用的getWidth
和getHeight
方法:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
For the use case you're describing however, a margin/padding in the layout seems more appropriate.
但是,对于您描述的用例,布局中的边距/填充似乎更合适。
Another way is: DisplayMetrics
另一种方法是:DisplayMetrics
A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:
一种描述有关显示的一般信息的结构,例如其大小、密度和字体缩放。要访问 DisplayMetrics 成员,请像这样初始化一个对象:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
We can use widthPixels
to get information for:
我们可以widthPixels
用来获取以下信息:
"The absolute width of the display in pixels."
“显示的绝对宽度(以像素为单位)。”
Example:
例子:
Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);
回答by Balaji.K
One way is:
一种方法是:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
It is deprecated, and you should try the following code instead. The first two lines of code gives you the DisplayMetrics
objecs. This objects contains the fields like heightPixels
, widthPixels
.
它已被弃用,您应该尝试使用以下代码。前两行代码为您提供了DisplayMetrics
对象。此对象包含诸如heightPixels
,之类的字段widthPixels
。
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
回答by Francesco Feltrinelli
It may not answer your question, but it could be useful to know (I was looking for it myself when I came to this question) that if you need a View's dimension but your code is being executed when its layout has not been laid out yet (for example in onCreate()
) you can setup a ViewTreeObserver.OnGlobalLayoutListener
with View.getViewTreeObserver().addOnGlobalLayoutListener()
and put the relevant code that needs the view's dimension there. The listener's callback will be called when the layout will have been laid out.
它可能无法回答您的问题,但知道(我在遇到这个问题时自己正在寻找它)可能很有用(例如在onCreate()
)中,您可以设置一个ViewTreeObserver.OnGlobalLayoutListener
withView.getViewTreeObserver().addOnGlobalLayoutListener()
并将需要视图维度的相关代码放在那里。布局完成后,将调用侦听器的回调。
回答by digiphd
(2012 answer, may be out of date) If you want to support pre Honeycomb, you will need to put in backward compatibility prior to API 13. Something like:
(2012 答案,可能已过时)如果您想支持蜂窝之前,则需要在 API 13 之前实现向后兼容性。例如:
int measuredWidth = 0;
int measuredHeight = 0;
WindowManager w = getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
w.getDefaultDisplay().getSize(size);
measuredWidth = size.x;
measuredHeight = size.y;
} else {
Display d = w.getDefaultDisplay();
measuredWidth = d.getWidth();
measuredHeight = d.getHeight();
}
Of course the deprecated methods will eventually be taken out of the the most recent SDKs, but while we still rely on most of our users having Android 2.1, 2.2 and 2.3, this is what we are left with.
当然,弃用的方法最终会从最新的 SDK 中删除,但虽然我们仍然依赖大多数拥有 Android 2.1、2.2 和 2.3 的用户,但我们只剩下这些。
回答by Dragan Marjanovi?
I have tried all possible "solutions" unsuccessfully and I noticed that Elliott Hughes' "Dalvik Explorer" app always shows correct dimension on any Android device/OS version. I ended up looking at his open source project that can be found here: https://code.google.com/p/enh/
我尝试了所有可能的“解决方案”都没有成功,我注意到 Elliott Hughes 的“Dalvik Explorer”应用程序在任何 Android 设备/操作系统版本上总是显示正确的尺寸。我最终查看了他的开源项目,可以在这里找到:https: //code.google.com/p/enh/
Here's all the relevant code:
这是所有相关代码:
WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
try {
// used when 17 > SDK_INT >= 14; includes window decorations (statusbar bar/menu bar)
widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
try {
// used when SDK_INT >= 17; includes window decorations (statusbar bar/menu bar)
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
widthPixels = realSize.x;
heightPixels = realSize.y;
} catch (Exception ignored) {
}
EDIT: slightly improved version (avoid firing exceptions on non-supported OS version):
编辑:稍微改进的版本(避免在不支持的操作系统版本上触发异常):
WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
try {
widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 17)
try {
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
widthPixels = realSize.x;
heightPixels = realSize.y;
} catch (Exception ignored) {
}
回答by Zelleriation
Simplest way:
最简单的方法:
int screenHeight = getResources().getDisplayMetrics().heightPixels;
int screenWidth = getResources().getDisplayMetrics().widthPixels;
回答by Swapnil Sonar
For accessing the height of the status bar for Android devices, we prefer a programmatic way to get it:
为了访问 Android 设备状态栏的高度,我们更喜欢以编程方式获取它:
Sample code
示例代码
int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
result = getResources().getDimensionPixelSize(resId);
}
The variable result
gives the height in the pixel.
该变量result
给出了像素的高度。
For quick access
为了快速访问
For more information about height of Title bar
, Navigation bar
and Content View
, kindly look on Android Device Screen Sizes.
有关高度的更多信息Title bar
,Navigation bar
以及Content View
,在亲切的样子Android设备屏幕尺寸。
回答by Marcin Gil
First get view (eg. by findViewById()
) and then you can use getWidth()on the view itself.
首先获取视图(例如 by findViewById()
),然后您可以在视图本身上使用getWidth()。
回答by Jorgesys
I have two functions, one for sending the context and the other getting height and width in pixels:
我有两个函数,一个用于发送上下文,另一个用于以像素为单位获取高度和宽度:
public static int getWidth(Context mContext){
int width=0;
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if(Build.VERSION.SDK_INT>12){
Point size = new Point();
display.getSize(size);
width = size.x;
}
else{
width = display.getWidth(); // Deprecated
}
return width;
}
and
和
public static int getHeight(Context mContext){
int height=0;
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if(Build.VERSION.SDK_INT>12){
Point size = new Point();
display.getSize(size);
height = size.y;
}
else{
height = display.getHeight(); // Deprecated
}
return height;
}
回答by Pijusn
This is the code I use for the task:
这是我用于任务的代码:
// `activity` is an instance of Activity class.
Display display = activity.getWindowManager().getDefaultDisplay();
Point screen = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
display.getSize(screen);
} else {
screen.x = display.getWidth();
screen.y = display.getHeight();
}
Seems clean enough and yet, takes care of the deprecation.
看起来足够干净,但是,照顾了弃用。