关于 异形屏/刘海屏/挖孔屏 的适配

566 阅读1分钟

部分文章

  1. 谷歌官方流海适配方案
  2. 挖孔屏适配小结 本地验证可用
  3. Google官方文档 支持刘海屏
  4. 一大波 Android 刘海屏来袭,全网\Maybe/最全适配技巧!
  5. 刘海屏适配最佳实践-引导页、沉浸式小说阅读页
  6. “沉浸式”体验?异形屏适配?我把他们扒光了明明白白告诉你应该这样做

关键工具类: DisplayCutout

private void setCutOutMode(){
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
        //使内容出现在status bar后边,如果要使用全屏的话再加上View.SYSTEM_UI_FLAG_FULLSCREEN
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        //lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
        //lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
        //lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT;
        //设置页面延伸到刘海区显示
        getWindow().setAttributes(lp);
        getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @Override
            public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) {
                DisplayCutout cutout = windowInsets.getDisplayCutout();
                if (cutout == null) {
                    Log.e("CutoutTAG", "cutout==null, is not notch screen");//通过cutout是否为null判断是否刘海屏手机
                } else {
                    List<Rect> rects = cutout.getBoundingRects();
                    if (rects == null || rects.size() == 0) {
                        Log.e("CutoutTAG", "rects==null || rects.size()==0, is not notch screen");
                    } else {
                        Log.e("CutoutTAG", "rect size:" + rects.size());//注意:刘海的数量可以是多个
                        for (Rect rect : rects) {
                            Log.e("CutoutTAG", "cutout.getSafeInsetTop():" + cutout.getSafeInsetTop()
                                    + ", cutout.getSafeInsetBottom():" + cutout.getSafeInsetBottom()
                                    + ", cutout.getSafeInsetLeft():" + cutout.getSafeInsetLeft()
                                    + ", cutout.getSafeInsetRight():" + cutout.getSafeInsetRight()
                                    + ", cutout.rects:" + rect
                            );
                        }
                    }
                }
                return windowInsets;
            }
        });
    }
}