问题描述
我创建了一些自定义元素,我想以编程方式将它们放置在右上角(顶部边缘 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;
如何在主Activity中获取screenWidth
和screenHeight
?
How do I get screenWidth
and screenHeight
in the main Activity?
推荐答案
如果你想要以像素为单位的显示尺寸,你可以使用 getSize
:
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 中),您可以使用现已弃用的 getWidth
和 getHeight
方法:
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);
API 30 级更新
final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
// Gets all excluding insets
final WindowInsets windowInsets = metrics.getWindowInsets();
Insets insets = windowInsets.getInsetsIgnoreVisibility(WindowInsets.Type.navigationBars()
| WindowInsets.Type.displayCutout());
int insetsWidth = insets.right + insets.left;
int insetsHeight = insets.top + insets.bottom;
// Legacy size that Display#getSize reports
final Rect bounds = metrics.getBounds();
final Size legacySize = new Size(bounds.width() - insetsWidth,
bounds.height() - insetsHeight);
这篇关于如何在Android中将屏幕尺寸作为像素获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!