如何检测设备是否支持缺口显示?

时间:2018-09-26 09:12:54

标签: android

当前,我在检测移动设备是否支持android中的缺口显示时遇到问题。

有人可以帮助我吗? (我需要使用android studio中的代码来完成此操作)

谢谢。

4 个答案:

答案 0 :(得分:6)

如果您要支持所有操作系统,则某些Oreo设备也会显示缺口,那么您可以使用我的解决方案。根据材料设计指南,Android设备的状态栏高度为24dp。您可以使用以下方法获取设备状态栏的高度和设备密度,并检查状态栏的高度是否大于24dp。如果其高度大于24dp,则显示为缺口,然后您可以根据需要处理视图位置。这也适用于奥利奥(Oreo)。

int statusBarHeight = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
    statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}

// DP转换为像素

public static int convertDpToPixel ( float dp){
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return Math.round(px);
}

//根据您的要求进行UI调整

if (statusBarHeight > convertDpToPixel(24)) {
    RelativeLayout.LayoutParams topbarLp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    topbarlp.setMargins(0, statusBarHeight, 0, 0);
    topbar.setLayoutParams(topbarlp)
}

答案 1 :(得分:4)

市场上仅有少数带有notch的设备,并且目前尚无法检测到设备是否具有带有Android API的陷波屏(Android

但是,作为一种解决方法,请检查设备名称,然后确定它们是否具有槽口,并相应地执行工作,那里有一个可以轻松检测设备名称的库:

https://github.com/jaredrummler/AndroidDeviceNames

但使用Android P Google provided notch support

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    DisplayCutout displayCutout = getWindow().getDecorView().getRootWindowInsets().getDisplayCutout();
}

答案 2 :(得分:1)

您需要使用getDisplayCutout对象的WindowInsets方法。这将为您提供一个DisplayCutout对象,您可以查询该对象以找到显示屏中的“安全”插图。

DisplayCutout类是API级别28中的新增功能,因此您将无法在API级别较低的设备上执行此操作(您可以假定除非API级别> = 28,否则没有缺口)。

有一个指南here

您可以通过重写View的onApplyWindowInsets方法或实现一个OnApplyWindowInsetsListener类来获取WindowInsets对象。

答案 3 :(得分:1)

我强烈建议使用该库react-native-device-info,因为版本为0.24.0,所以我们使用的函数名hasNotch()非常有效。在我的生产应用中进行了测试。

相关问题