天天看點

Android适配全面屏/劉海屏

目前國内廠商已經推出的劉海屏Android手機有華為P20 pro, vivo X21,OPPO R15。

1.華為劉海屏的官方适配文檔 

https://devcenter-test.huawei.com/consumer/cn/devservice/doc/50114

2.oppo劉海屏官方文檔:

https://open.oppomobile.com/service/message/detail?id=61876

3.vivo劉海屏官方文檔:

https://dev.vivo.com.cn/doc/document/info?id=103

vivo 和 OPPO官網僅僅給出了适配指導,沒有給出具體方案,簡單總結為:

如有是具有劉海屏的手機,豎屏顯示狀态欄,橫屏不要在危險區顯示重要資訊或者設定點選事件

4.google官方劉海屏适配方案

google從Android P開始為劉海屏提供支援,目前提供了一個類和三種模式:

一個類

The new 

DisplayCutout

 class lets you find out the location and shape of the non-functional areas where content shouldn't be displayed. To determine the existence and placement of these cutout areas, use the

getDisplayCutout()

 method

就是說可以用DisplayCutout這個類找出劉海(cutout)的位置和形狀,調用getDisplayCutout()這個方法可以擷取劉海(cutout)的位置和區域

是以我們可用這個類判斷是否有劉海的存在以及劉海的位置

DisplayCutout cutout = mContext.getDisplayCutout();
           

三種模式

A new window layout attribute, 

layoutInDisplayCutoutMode

, allows your app to lay out its content around a device's cutouts. You can set this attribute to one of the following values:

  • LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT

  • LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES

  • LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER

layoutInDisplayCutoutMode值說明:

LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT:預設情況下,全屏視窗不會使用到劉海區域,非全屏視窗可正常使用劉海區域

LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS:視窗聲明使用劉海區域

LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER:視窗聲明不使用劉海區域

适配方案:

我們可以設定是否允許window擴充到劉海區:

WindowManager.LayoutParams lp =getWindow().getAttributes();

lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;

getWindow().setAttributes(lp);

例如一個有狀态欄的頁面, 我們可以這樣适配:

DisplayCutout cutout = getDisplayCutout();
if(cutout != null){
 WindowManager.LayoutParams lp =getWindow().getAttributes();  
 lp.layoutInDisplayCutoutMode=WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;  
 getWindow().setAttributes(lp);
}
           

需要注意的是:谷歌提供的劉海屏适配方案,要求應用必須适配到P版本才可使用。

繼續閱讀