如何在 Android 中获取屏幕尺寸(像素)
我创建了一些自定义元素,我想以编程方式将它们放置在右上角(距上边缘 n
像素,距右边缘 m
像素)。 因此,我需要获取屏幕宽度和屏幕高度,然后设置位置:
int px = screenWidth - m;
int py = screenHeight - n;
How do I get screenWidth
and screenHeight
in the main Activity?
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;
How do I get screenWidth
and screenHeight
in the main Activity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
最简单的方法:
Simplest way:
为了访问 Android 设备状态栏的高度,我们更喜欢通过编程方式来获取它:
示例代码
变量
result
给出以像素为单位的高度。如需快速访问
有关
标题栏
高度的更多信息,导航栏
和内容视图
,请在Android设备上查看屏幕尺寸。For accessing the height of the status bar for Android devices, we prefer a programmatic way to get it:
Sample code
The variable
result
gives the height in the pixel.For quick access
For more information about height of
Title bar
,Navigation bar
andContent View
, kindly look on Android Device Screen Sizes.首先获取视图(例如通过
findViewById()
),然后您可以使用 getWidth() 在视图本身上。First get view (eg. by
findViewById()
) and then you can use getWidth() on the view itself.我有两个函数,一个用于发送上下文,另一个用于获取以像素为单位的高度和宽度:
和
I have two functions, one for sending the context and the other getting height and width in pixels:
and
对于使用 XML 进行动态缩放,有一个名为“android:layout_weight”的属性
下面的示例根据 synic 在 此线程,显示一个占据屏幕 75% 的按钮(权重 = .25)和一个占据屏幕剩余 25% 的文本视图(权重 = .75) )。
For dynamically scaling using XML there is an attribute called "android:layout_weight"
The below example, modified from synic's response on this thread, shows a button that takes up 75% of the screen (weight = .25) and a text view taking up the remaining 25% of the screen (weight = .75).
这是我用于该任务的代码:
看起来足够干净,但仍处理弃用问题。
This is the code I use for the task:
Seems clean enough and yet, takes care of the deprecation.
这不是一个更好的解决方案吗? DisplayMetrics 附带您需要的一切,并可从 API 1 开始工作。
您还可以使用 getRealMetrics,但这仅适用于 17+。
我错过了什么吗?
Isn't this a much better solution? DisplayMetrics comes with everything you need and works from API 1.
You can also get the actual display (including screen decors, such as Status Bar or software navigation bar) using getRealMetrics, but this works on 17+ only.
Am I missing something?
只是添加到弗朗西斯科的答案中。 如果您想找出窗口中的位置或屏幕中的位置,另一个更合适的观察者是
ViewTreeObserver.OnPreDrawListener()
这也可用于查找视图的其他属性在 onCreate() 时大部分是未知的,例如滚动位置、缩放位置。
Just adding to Francesco's answer. The other observer that is more apt, if you want to find out the location in window or location in screen is
ViewTreeObserver.OnPreDrawListener()
This also can be used to find other attributes of a view that is mostly unknown at onCreate() time e.g. the scrolled position, the scaled position.
查找屏幕的宽度和高度:
使用它,我们可以获得最新及以上的SDK 13。
Find width and height of the screen:
Using this, we can get the latest and above SDK 13.
在 Activity 中使用以下代码。
Using the following code in Activity.
需要说的是,如果您不在
Activity
中,而是在View
中(或者在您的作用域中有View
类型的变量),则有不需要使用WINDOW_SERVICE
。 那么你至少可以使用两种方式。第一:
第二:
我们在这里调用的所有这些方法都没有被弃用。
Need to say, that if you are not in
Activity
, but inView
(or have variable ofView
type in your scope), there is not need to useWINDOW_SERVICE
. Then you can use at least two ways.First:
Second:
All this methods we call here is not deprecated.
这不是OP的答案,因为他想要以实际像素为单位的显示尺寸。 我想要“设备独立像素”中的尺寸,并从这里汇总答案 https://stackoverflow.com/a/17880012 /253938 和这里 https://stackoverflow.com/a/6656774/253938 我想出了这个:
This is not an answer for the OP, as he wanted the display dimensions in real pixels. I wanted the dimensions in "device-independent-pixels", and putting together answers from here https://stackoverflow.com/a/17880012/253938 and here https://stackoverflow.com/a/6656774/253938 I came up with this:
要获取屏幕尺寸,请使用显示度量
获取高度和宽度(以像素为单位)
For getting the screen dimensions use display metrices
Get the height and width in pixels
我发现这成功了。
I found this did the trick.
您可以使用 : 获取高度尺寸,使用以下
方式获取宽度尺寸
You can do get the height size using :
and the width size using
有一种未弃用的方法可以使用 DisplayMetrics (API 1) 来执行此操作,从而避免 try/catch 混乱:
There is a non-deprecated way to do this using DisplayMetrics (API 1), that avoids the try/catch messiness:
我将像这样包装 getSize 代码:
I would wrap the getSize code like this:
对于正在寻找没有状态栏和操作栏的可用屏幕尺寸的人(也感谢 Swapnil 的回答):
For who is searching for usable screen dimension without Status Bar and Action Bar (also thanks to Swapnil's answer):
科特林
Kotlin
首先加载 XML 文件,然后编写以下代码:
根据屏幕分辨率显示宽度和高度。
First load the XML file and then write this code:
Show width and height according your screen resolution.
请按照以下方法操作:
Follow the methods below:
在 Kotlin 中要简单得多。
Much simpler in Kotlin.
有时,您需要在活动的 onCreate 中了解布局可用空间的精确尺寸。
经过一番思考,我想出了这样的做法。
如果由于某种原因您不想将另一个 Activity 添加到 Android 清单中,您可以这样做:
There are times when you need to know the precise dimensions of the available space for a layout when in an activity's onCreate.
After some thought I worked out this way of doing it.
If for some reason you don't want to add another activity to the Android manifest, you can do it this way:
如果您不想要 WindowManagers、Points 或 Displays 的开销,则可以获取 XML 中最顶层视图项的高度和宽度属性,前提是其高度和宽度设置为 match_parent。 (只要您的布局占据整个屏幕,情况就是如此。)
例如,如果您的 XML 以类似以下内容开头:
则
findViewById(R.id.entireLayout).getWidth()
将返回屏幕的宽度,findViewById(R.id.entireLayout).getHeight()
将返回屏幕的高度。If you don't want the overhead of WindowManagers, Points, or Displays, you can grab the height and width attributes of the topmost View item in your XML, provided its height and width are set to match_parent. (This is true so long as your layout takes up the entire screen.)
For example, if your XML starts with something like this:
Then
findViewById(R.id.entireLayout).getWidth()
will return the screen's width andfindViewById(R.id.entireLayout).getHeight()
will return the screen's height.对于 API 级别 30,
WindowMetrics将使用.getBounds
。 其用法示例可以在链接文档中找到:旧答案:
如果您想要以像素为单位的显示尺寸,您可以使用
getSize
:如果您不在
Activity
中,您可以获得通过WINDOW_SERVICE
默认的Display
:如果您位于片段中并且想要完成此操作,只需使用 Activity.WindowManager(在 Xamarin.Android 中)或 getActivity().getWindowManager() (在java中)。
在引入
getSize
之前(在 API 级别 13 中),您可以使用现已弃用的getWidth
和getHeight
方法:对于该用例,然而,您所描述的布局中的边距/填充似乎更合适。
另一种方法是: DisplayMetrics
我们可以使用
widthPixels
获取以下信息:示例:
For API Level 30,
WindowMetrics.getBounds
is to be used. An example of its usage can be found in the linked docs:Old answer:
If you want the display dimensions in pixels you can use
getSize
:If you're not in an
Activity
you can get the defaultDisplay
viaWINDOW_SERVICE
:If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).
Before
getSize
was introduced (in API level 13), you could use thegetWidth
andgetHeight
methods that are now deprecated:For the use case, you're describing, however, a margin/padding in the layout seems more appropriate.
Another way is: DisplayMetrics
We can use
widthPixels
to get information for:Example:
它可能无法回答您的问题,但如果您需要视图的尺寸,但您的代码在其布局尚未布局时正在执行,那么了解(当我遇到这个问题时我自己正在寻找它)可能会很有用(例如在
onCreate()
中)您可以使用View.getViewTreeObserver().addOnGlobalLayoutListener()
设置一个ViewTreeObserver.OnGlobalLayoutListener
并放置相关的那里需要视图尺寸的代码。 布局完成后,将调用侦听器的回调。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 aViewTreeObserver.OnGlobalLayoutListener
withView.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.(2012年的答案,可能已经过时)如果你想支持Honeycomb之前的版本,你需要在API 13之前加入向后兼容性。类似这样的:
当然,不推荐使用的方法最终会从最新的SDK中删除,虽然我们仍然依赖大多数使用 Android 2.1、2.2 和 2.3 的用户,但这就是我们所剩下的。
(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:
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.
我已经尝试了所有可能的“解决方案”,但均未成功,并且我注意到 Elliott Hughes 的“Dalvik Explorer”应用程序始终在任何 Android 设备/操作系统版本上显示正确的尺寸。 我最终查看了他的开源项目,可以在这里找到:https://code.google.com/p/enh/
这是所有相关代码:
编辑:略有改进的版本(避免在不支持的操作系统版本上引发异常):
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/
Here's all the relevant code:
EDIT: slightly improved version (avoid firing exceptions on non-supported OS version):