您可以使用DisplayMetrics
获取有关您的应用程序运行的屏幕的大量信息。
首先,我们创建一个DisplayMetrics
指标对象:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
由此,我们可以获得显示尺寸所需的信息:
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
这将返回宽度和高度的绝对值(以像素为单位),因此对于 Galaxy SIII、Galaxy Nexus 等为 1280x720。
这本身通常没有帮助,因为当我们在 Android 设备上工作时,我们通常更喜欢在与密度无关的像素、dip 中工作。
You get the density
of the screen using metrics
again, in the form of a scale factor for the device, which is based on the Android Design Resources for mdpi
, hdpi
etc.
![DPI scales](https://i.stack.imgur.com/UR86h.png)
float scaleFactor = metrics.density;
根据这个结果,我们可以计算出特定高度或宽度的密度无关像素的数量。
float widthDp = widthPixels / scaleFactor
float heightDp = heightPixels / scaleFactor
从中获得的结果将帮助您决定与什么类型的屏幕一起使用Android 配置示例,它为您提供每个屏幕尺寸的相对 dp:
- 320dp:典型的手机屏幕(240x320 ldpi、320x480 mdpi、480x800 hdpi 等)。
- 480dp:类似于 Streak (480x800 mdpi) 的中间平板电脑。
- 600dp:7 英寸平板电脑 (600x1024 mdpi)。
- 720dp:10 英寸平板电脑(720x1280 mdpi、800x1280 mdpi 等)。
根据以上信息,我们知道,如果设备的最小宽度大于 600dp,则该设备是 7 英寸平板电脑,如果大于 720dp,则该设备是 10 英寸平板电脑。
我们可以使用以下公式计算出最小宽度min
的函数Math
类,通过heightDp
和widthDp
返回smallestWidth
.
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
//Device is a 10" tablet
}
else if (smallestWidth > 600) {
//Device is a 7" tablet
}
然而,这并不总能为您提供精确的匹配,尤其是在使用不起眼的平板电脑时,这些平板电脑可能会将其密度错误地表示为 hdpi,而事实并非如此,或者可能只有 800 x 480 像素但仍显示在 7 英寸屏幕上。
除了这些方法之外,如果您需要知道设备的确切尺寸(以英寸为单位),您也可以使用metrics
方法计算每英寸屏幕有多少个像素。
float widthDpi = metrics.xdpi;
float heightDpi = metrics.ydpi;
您可以利用每英寸设备中有多少像素以及总像素数的知识来计算出设备有多少英寸。
float widthInches = widthPixels / widthDpi;
float heightInches = heightPixels / heightDpi;
这将返回设备的高度和宽度(以英寸为单位)。这对于确定设备类型并不总是那么有帮助,因为设备的广告尺寸是对角线,我们拥有的只是高度和宽度。
然而,我们也知道,给定三角形的高度和宽度,我们可以使用毕达哥拉斯定理计算出斜边的长度(在本例中为屏幕对角线的大小)。
//a² + b² = c²
//The size of the diagonal in inches is equal to the square root of the height in inches squared plus the width in inches squared.
double diagonalInches = Math.sqrt(
(widthInches * widthInches)
+ (heightInches * heightInches));
由此,我们可以判断该设备是否是平板电脑:
if (diagonalInches >= 10) {
//Device is a 10" tablet
}
else if (diagonalInches >= 7) {
//Device is a 7" tablet
}
这就是您计算正在使用的设备类型的方法。