gpt4 book ai didi

android - 通过代码区分安卓设备 [8inch vs 10 inch tablet]

转载 作者:可可西里 更新时间:2023-10-31 22:04:17 33 4
gpt4 key购买 nike

我正在为两个特定设备编写我的应用程序

Dell Venue 8 8inch

Samsung Galaxy Note 10.1 10inch

在我的代码中,我想为一个小模块为这些设备中的每一个编写不同的代码,但我无法区分这两者

我用过

double density = getResources().getDisplayMetrics().density;

但两者返回相同1.3312500715255737

使用 getDisplayMetrics()

我试图获得解决方案,但两者都返回相同的结果

1280x720

那么我在代码中使用什么来区分这两种设备?

最佳答案

您可以使用 DisplayMetrics 获取有关您的应用运行屏幕的大量信息。

首先,我们创建一个 DisplayMetrics 指标对象:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;

这将返回以像素为单位的宽度和高度的绝对值,因此 Galaxy SIII、Galaxy Nexus 等为 1280x720。

这本身通常没有帮助,因为当我们在 Android 设备上工作时,我们通常更喜欢在密度独立像素、dip 上工作。

float scaleFactor = displaymetrics .density;

根据这个结果,我们可以计算特定高度或宽度的密度无关像素的数量。

float widthDp = widthPixels / scaleFactor
float heightDp = heightPixels / scaleFactor

根据以上信息,我们知道如果设备的最小宽度大于 600dp,则设备为 7"平板电脑,如果大于 720dp,则设备为 10"平板电脑。

我们可以使用 Math 类的 min 函数计算出最小宽度,传入 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"屏幕。

除了这些方法之外,如果您需要知道设备的确切尺寸(以英寸为单位),您也可以使用度量方法计算每英寸屏幕有多少像素。

float widthDpi = displaymetrics .xdpi;
float heightDpi = displaymetrics .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
}

关于android - 通过代码区分安卓设备 [8inch vs 10 inch tablet],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29892734/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com