如何在Android中以像素为单位获取屏幕尺寸 [英] How to get screen dimensions as pixels in Android

查看:220
本文介绍了如何在Android中以像素为单位获取屏幕尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一些自定义元素,我想以编程方式将它们放置在右上角(顶部边缘为n像素,右侧边缘为m像素).因此,我需要获取屏幕宽度和屏幕高度,然后设置位置:

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:

int px = screenWidth - m;
int py = screenHeight - n;

如何在主要活动中获取screenWidthscreenHeight?

How do I get screenWidth and screenHeight in the main Activity?

推荐答案

如果要以像素为单位显示尺寸,可以使用

If you want the display dimensions in pixels you can use getSize:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

如果您不在Activity中,则可以通过WINDOW_SERVICE获取默认的Display:

If you're not in an Activity you can get the default Display via WINDOW_SERVICE:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

如果您要处理一个片段,只需使用Activity.WindowManager(在Xamarin.Android中)或getActivity().getWindowManager()(在Java中)即可.

If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).

在引入getSize之前(在API级别13中),可以使用现在不推荐使用的getWidthgetHeight方法:

Before getSize was introduced (in API level 13), you could use the getWidth and getHeight methods that are now deprecated:

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.

另一种方法是: 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 metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

我们可以使用widthPixels获取以下信息:

We can use widthPixels to get information for:

显示器的绝对宽度(以像素为单位)."

"The absolute width of the display in pixels."

示例:

Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);

这篇关于如何在Android中以像素为单位获取屏幕尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆