android刘海屏的适配

场景

沉浸式场景,由于刘海屏,刘海位置会对内容有遮挡,为了让内容展示完全,需要对刘海屏进行适配。刘海屏 宽度、高度形状均略有差异,适配难度也比较高。
如下图,适配即处理好Notch遮挡,与耳朵区显示问题。
在这里插入图片描述

适配

android P开始提供刘海屏相关api.针对android P及以后的版本,可以使用android API适配。 但有些厂商(小米,华为等)在android P之前(android O版本)已经支持刘海屏。
需要注意的问题:

  • 沉浸式需要适配。其他不需要适配。
  • 刘海的高度 不超过 状态栏的高度,可通过填充状态栏,做简单适配。
  • 当应用不显示 status bar 时(如全屏游戏),不允许应用使用耳朵区,系统默认填黑。

android官方适配

android P开始支持刘海屏。
提供的常用api有:

  • 获取耳朵区域
  • 获取安全距离
//android P获取刘海屏区域
if (Build.VERSION.SDK_INT >= 28) {
        //android P以上使用google 官方判断
    View decorView = getWindow().getDecorView();
    WindowInsets windowInsets = decorView.getRootWindowInsets();
    if (windowInsets != null) {
        DisplayCutout cutout = windowInsets.getDisplayCutout();
        if (cutout != null) {
            List<Rect> list = cutout.getBoundingRects();
            //list rect即为刘海区域,左上角,右下角坐标
        }
    }
}

//android P获取获取刘海屏安全距离
if (Build.VERSION.SDK_INT >= 28){
    View decorView = window.getDecorView();
    WindowInsets windowInsets = decorView.getRootWindowInsets();
    if (windowInsets != null) {
        DisplayCutout cutout = windowInsets.getDisplayCutout();
        if(cutout != null) {
            //获取顶部安全距离
            return cutout.getSafeInsetTop();
        }
    }
    return 0;
}

但是,其他一些操作,官方文档中没有,例如:关闭刘海屏。这种能力需要针对机型,对接具体厂商适配。

厂商api适配

当系统版本为android O时,需要用厂商提供的api适配。

有些接口要用反射来做。例如小米,判断是否为刘海屏

    /**
     * 只适用于判断MIUI 是否有刘海屏
     * SystemProperties.getInt("ro.miui.notch", 0) == 1;
     *
     * @return true,小米手机为刘海屏
     */
    private static boolean hasMIUINotchInScreen() {
        try {
            Class<?> clz = Class.forName("android.os.SystemProperties");
            Method get = clz.getMethod("getInt", String.class, int.class);
            return (int) get.invoke(clz, "ro.miui.notch", -1) == 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

刘海屏关闭需要厂商提供的api
目前,小米和华为的手机支持,关闭刘海屏,这时会在顶部刘海屏相当高度,贴一层黑条。

    /**
     * 刘海屏是否关闭
     * @param contentResolver ContentResolver
     * @return true 刘海屏关闭
     */
    public static boolean isNorchClose(ContentResolver contentResolver) {
        if(isMIUI()) {
            return Settings.Global.getInt(contentResolver, "force_black", 0) == 1;
        } else if( isHuaWei() ) {
            return Settings.Secure.getInt(contentResolver,"display_notch_status", 0) == 1;
        }
        return false;
    }

参考

小米刘海屏android O适配
android 兼容所有刘海屏的方案大全
刘海屏适配整理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值