Android immersive analysis and wheel usage

Preface

Let's first review the general routines for implementing the immersive status bar. On Android, the operation of StatusBar (status bar) has been constantly improving, and the performance is getting better and better. Below Android4.4, we can display and hide StatusBar and NavigationBar. But until Android4.4, we can realize the immersive status bar in a real sense. From Android4.4 to the present (Android 9), the immersion can be roughly divided into three stages:

  • Android4.4 (API 19)-Android 5.0 (API 21): At this stage, immersion can be achieved, but the performance is not very good. The implementation method is: Set the status bar to transparent and full screen mode through FLAG TRANSLUCENT STATUS, and then pass Add a View the same size as the StatusBar, and set the background of the View to the color we want to achieve immersion.
  • Android 5.0 (API 21) and above: In Android 5.0, an important attribute and method android:statusBarColor (corresponding method is setStatusBarColor) was added, through this method we can easily achieve immersion. In other words, starting from Android 5.0, the system truly supports immersion.
  • Android 6.0 (API 23) and above: In fact, the implementation of Android 6.0 and above is the same as Android 5.0. Why should it be classified as a separate important stage? It is because starting from Android 6.0 (API 23), we can change the drawing mode of the status bar, which can display white or light black content and icons (except for Meizu phones, Meizu has its own source code changes, which can be achieved under 6.0).

Summary: The API versions on Android in these three stages are chaotic, and various Flags stand out. Coupled with the customization of major manufacturers, it can be said to add fuel to the fire, making Android developers a headache.

1. Immersive three-stage use

We will start from the three stages of immersion support and the functions of support, to understand the relevant background, and then to understand how to achieve the three stages of immersion.

1.1 Android4.0-Android5.0 setting immersive experience

In android4.4 and above, a new flag: SYSTEM UI FLAG IMMERSIVE is introduced for the setSystemUiVisibility() method , which can enable your app to achieve a true full-screen experience. When the three flags SYSTEM UI FLAG IMMERSIVE, SYSTEM UI FLAG HIDE NAVIGATION and SYSTEM UI FLAG_FULLSCREEN are used together, the status bar and navigation bar can be hidden, and your app can capture all touch screen events of the user. **From Android 4.4 and above, the immersive experience can be set, but it is only the display and hiding of the status bar and navigation bar**.

1.1.1 FLAG TRANSLUCENT STATUS

When the immersive full-screen mode is enabled, your activity will continue to receive various touch events. The user can slide inward on the edge of the original area of ​​the status bar and navigation bar to make the system bar redisplay. This operation clears the SYSTEM UI FLAG HIDE NAVIGATION and SYSTEM UI FLAG_FULLSCREEN . If there are no two signs, the system bar becomes visible again. If two labels are set, this operation also triggers View.OnSystemUiVisibilityChangeListener. However, if you want the system bar to hide automatically after a period of time, you should use the SYSTEM UI FLAG IMMERSIVE STICKY label .

Shows various "immersion" statesimage

In the picture above:

  • Non-immersive mode-shows the state before the application enters immersive mode. It also shows the status of the user sliding display system bar after setting the IMMERSIVE label. After the user swipes, SYSTEM UI FLAG HIDE NAVIGATION and SYSTEM UI FLAG_FULLSCREEN will be cleared, and the system bar will redisplay and remain visible. Please note that the best way is to keep all the UI controls synchronized with the display and hide of the system bar, which can reduce the state of the screen display and provide a more seamless and smooth user experience. Therefore, all UI controls are displayed along with the system bar. Once the application enters the immersive mode, the UI controls are also hidden along with the system bar. In order to ensure that the visibility of the UI is consistent with the system bar, we need a listener View.OnSystemUiVisibilityChangeListener to listen for changes in the system bar. This will be explained in detail in the next section.
  • Prompt bubble-when entering the immersive mode for the first time, the system will display a prompt bubble, prompting the user how to display the system bar again. Please note that if you want to force the display of prompt bubbles for testing purposes, you can first set the application to immersion mode, then press the power button to enter the lock screen mode, and turn on the screen after 5 seconds.
  • Immersive Mode-This picture shows the state of hiding the system bar and other UI controls. You can set IMMERSIVE and IMMERSIVE_STICKY to enter this state.
  • Sticky label-This is the UI state when you set the IMMERSIVE_STICKY label. The user will slide inward to show the system bar. The semi-transparent system bar will be displayed temporarily and will be automatically hidden after a period of time. The sliding operation will not clear any tabs, nor will it trigger the system UI visibility listener, because the temporarily displayed navigation bar is not considered a visible state.

Note that the label of the immersive class will only take effect when used with one or two of SYSTEM UI FLAG HIDE NAVIGATION and SYSTEM UI FLAG_FULLSCREEN . You can use only one of them, but generally you need to hide the status bar and the navigation bar at the same time to achieve an immersive effect.

1.1.2 Two ways to use this attribute:

  • In use, we usually need to consider that the status bar is displayed at the top without being hidden or obscured (other apps such as reading apps or game apps need to hide the top status bar), so only need to set by code FLAG TRANSLUCENT STATU :
 
 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

  • Set the property windowTranslucentStatus through the theme:
    <style name="Theme" parent="Theme.Design.Light.NoActionBar">
        <item name="android:windowTranslucentStatus">true</item>
    </style>

The effect is as follows:image

The effect is as shown in the figure above. It can be seen that the immersive effect is coming out, but there is also a problem. Our title bar and status bar overlap, which is equivalent to the height of the StatusBar moved up in the entire layout.

In order to return the title bar to its original position and adapt to the color of the title bar, we add a fake status bar View with the same size as the StatusBar above the title bar. The BackgroundColor of the View can be set to the same color as the title bar by itself. For other colors, this View serves as a placeholder. At this time, the title bar will move down the height of the StatusBar and return to its normal position.

The code for redrawing the height of the title bar by setting paddingTop is as follows:

 View statusBarView = mDecorView.findViewById(IMMERSION_STATUS_BAR_VIEW);
        if (statusBarView == null) {
            statusBarView = new View(mActivity);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    mBarConfig.getStatusBarHeight());
            params.gravity = Gravity.TOP;
            statusBarView.setLayoutParams(params);
            statusBarView.setVisibility(View.VISIBLE);
            statusBarView.setId(IMMERSION_STATUS_BAR_VIEW);
            mDecorView.addView(statusBarView);
        }
        if (mBarParams.statusBarColorEnabled) {
            statusBarView.setBackgroundColor(ColorUtils.blendARGB(mBarParams.statusBarColor,
                    mBarParams.statusBarColorTransform, mBarParams.statusBarAlpha));
        } else {
            statusBarView.setBackgroundColor(ColorUtils.blendARGB(mBarParams.statusBarColor,
                    Color.TRANSPARENT, mBarParams.statusBarAlpha));
        }

After adding the above code, the effect is as follows:

image

Through the above, the immersive status bar on Android 4.4 can be realized.

Summary: The steps for Android4.4-Android5.0 are to add the FLAG TRANSLUCENT STATUS Flag to the window , and then add a fake status bar. The immersive effect set by the above method between Android4.4-Android5.0 is like a map. , There is a black shadow gradient at the top of the status bar, which has been fixed in version 5.0 and above.

If it is a picture immersed in the status bar, there is no need to set this fake status bar, just set it, and FLAG TRANSLUCENT STATUS is OK. And in Android4.4-Android5.0, there is no attribute to change the status color, so the background color can only be changed by adding a fake status bar.

1.2 Set the background color of the status bar above Android5.0

Android 5.0 is a milestone version. Starting from Android 5.0, Google has introduced a new design specification Material Design, and native controls can achieve some cool UI dynamic effects. Starting from this version, google has added a more important method setStatusBarColor (corresponding attribute: android:statusBarColor), through this method, you can easily realize the immersive status bar. Methods as below

public abstract void setStatusBarColor(@ColorInt int color);

Pay attention to the notes of this method. If you want this method to take effect, you must also use it with a Flag, you must set FLAG DRAWS SYSTEM BAR BACKGROUNDS , and you cannot set FLAG TRANSLUCENT STATUS (Android 4.4 only uses this), so it cannot be mutually exclusive with 4.4 Shared. Therefore, you can set the font color of the status bar and navigation bar above Android 5.0 .

1.2.1 FLAGDRAWSSYSTEMBARBACKGROUNDS属性

Explanation: FLAG DRAWS SYSTEM BAR BACKGROUNDS is set, indicating that Window will be responsible for drawing the background of the system bar, drawing the system bar (status bar and navigation bar) with a transparent background, and then fill the corresponding area with the colors of getStatusBarColor() and getNavigationBarColor(). This is how the immersive navigation bar is implemented above Android 5.0.

Add the following code to achieve immersion:

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    //注意要清除 FLAG_TRANSLUCENT_STATUS flag
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    getWindow().setStatusBarColor(getResources().getColor(android.R.color.holo_red_light));

The effect is as follows:image

If you set the theme by setting the theme during development, you need to add the following themes under the values-v21 folder to achieve compatibility

<style name="Theme" parent="Theme.Design.Light.NoActionBar">
        <item name="android:windowTranslucentStatus">false</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/holo_red_light</item>
    </style>

1.2.2 The picture extends to the status bar

To extend the picture to the status bar in Android 5.0, just set windowTranslucentStatus and set statusBarColor to transparent. The theme mode is set as follows:

<style name="ImageTranslucentTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:windowTranslucentStatus">true</item>
        <!-- 设置statusBarColor 为透明-->
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

In the development process, the use of code to set windowTranslucentStatus requires the judgment of the version number to be compatible with Android 5.0 or lower and Android 5.0 or higher.

1.3 Android 6.0 implements light black status bar word color and icon

When using the immersive version below Android 6.0, you will encounter a problem, that is, the word color and icon color of the Android system status bar are white. When the status bar color is close to light, the content on the status bar cannot be seen clearly Up. Android 6.0 added a new attribute to solve this problem, the attribute is SYSTEM UI FLAG LIGHT STATUS_BAR .

1.3.1 SYSTEMUIFLAGLIGHTSTATUS_BAR

image

Explanation: The Flag added for the setSystemUiVisibility(int) method requests the status bar drawing mode, which can be compatible with the status bar with a bright background. It will take effect after FLAG DRAWS SYSTEM BAR BACKGROUNDSflag is set and FLAG TRANSLUCENT STATUSflag is cleared at the same time .

Set by code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}

The effect is as follows imageand you can also use attributes in the theme, and the theme needs to be placed in the values-v23 folder corresponding to Android 6.0 or higher to take effect:

<style name="Theme" parent="Theme.Design.Light.NoActionBar">
        <item name="android:windowTranslucentStatus">false</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/holo_red_light</item>
        <!-- Android 6.0以上 状态栏字色和图标为浅黑色-->
        <item name="android:windowLightStatusBar">true</item>
    </style>

2. The principle and use of ZanImmersionBar wheels

In the actual development process, we not only encounter the compatibility problems of the above three versions, but also need to consider such as: different mobile phone brands, dynamic status bar background, and Fragment need to have its own status bar color scene. Therefore, it is necessary to comprehensively consider multiple scenarios to meet the requirements of adapting to multiple development situations. Summarize the following scenarios:

image

After synthesizing the above scenarios and referencing the github example for encapsulation, the ZanImmersionBar wheel is obtained

2.1 Principle:

We hope to encapsulate the settings of immersive effects in one class, and we want to achieve all effects through one method, but many effects will have repeated setting steps, and there are too many methods for each effect to tell which one to use , So the setting of the immersive effect is divided into several steps, and if you want to set the individual effect, set the parameters through the method, and finally collect all the parameters through the init method and set the parameter attributes uniformly.

ZanImmersionBar.with(this).init();//该方法将进行以下步骤处理沉浸式
public void init() {
        //更新Bar的参数
        updateBarParams();
        //设置沉浸式
        setBar();
        //适配状态栏与布局重叠问题
        fitsLayoutOverlap();
        //适配软键盘与底部输入框冲突问题
        fitsKeyboard();
        //变色view
        transformView();
    }

The immersive setting process is as follows:

image

Among these steps, obtaining parameters and setting immersion must be passed. The following three settings are situations that may be encountered during development and are also setting parameters. If they are matched, they will be processed for three settings. Next, the main analysis Next first step and second step.

2.1.1 Collect bar parameters

We use an object to store the bar parameters set by the user. These parameters include the status bar and navigation bar color, transparency, display and hide, etc., which are set separately through the parameters in the object

public class BarParams implements Cloneable {
    /**
     * 状态栏颜色
     */
    @ColorInt
    int statusBarColor = Color.TRANSPARENT;
    /**
     * 导航栏颜色
     */
    @ColorInt
    int navigationBarColor = Color.BLACK;
    /**
     * The Default navigation bar color.
     */
    int defaultNavigationBarColor = Color.BLACK;
    /**
     * 状态栏透明度
     */
    @FloatRange(from = 0f, to = 1f)
    float statusBarAlpha = 0.0f;
    /**
     * 导航栏透明度
     */
    @FloatRange(from = 0f, to = 1f)
    float navigationBarAlpha = 0.0f;
      //等其他属性
    ...
}

And these properties can be personalized through the following methods provided by ZanImmersionBar, and these methods just add the parameters that need to be set to the BarParams object, and finally you must call init to set the parameters.

 ZanImmersionBar.with(this)
             .transparentStatusBar()  //透明状态栏,不写默认透明色
             .transparentNavigationBar()  //透明导航栏,不写默认黑色(设置此方法,fullScreen()方法自动为true)
             .transparentBar()             //透明状态栏和导航栏,不写默认状态栏为透明色,导航栏为黑色(设置此方法,fullScreen()方法自动为true)
             .statusBarColor(R.color.colorPrimary)     //状态栏颜色,不写默认透明色
             .navigationBarColor(R.color.colorPrimary) //导航栏颜色,不写默认黑色
             .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色,不写默认状态栏为透明色,导航栏为黑色
             .statusBarAlpha(0.3f)  //状态栏透明度,不写默认0.0f
             .navigationBarAlpha(0.4f)  //导航栏透明度,不写默认0.0F
             .barAlpha(0.3f)  //状态栏和导航栏透明度,不写默认0.0f
             .statusBarDarkFont(true)   //状态栏字体是深色,不写默认为亮色
             .navigationBarDarkIcon(true) //导航栏图标是深色,不写默认为亮色
                           //等一些其他方法
             .init();  //必须调用方可沉浸式

After setting the parameters, you need to collect these parameters. If used in Fragment, you need to synchronize the BarParams parameter of the Fragment with Activity

//获得Bar相关信息
//如果在Fragment中使用,让Activity同步Fragment的BarParams参数
if (mIsFragment) {
    ZanImmersionBar immersionBar = mImmersionBarMap.get(mActivity.toString());
    if (immersionBar != null) {
        immersionBar.mBarParams = mBarParams;
    }
}

mImmersionBarMap is a Map, used to store the ZanImmersionBar object corresponding to each Activity

  • Principle: In fact, through the immersive three-generation development history, we can know that setting immersive is achieved by changing the window properties of Activity to achieve immersive, so we want to customize immersive in Fragment, in fact, by changing the BarParams parameter of Activity Set the immersive type of Activity, so you need to pay attention to the init initialization of ZanImmersionBar before setting the immersive type of Fragment.
  • Another example: It should be noted that dialogFragment and Dialog have their own window, which is a child window belonging to the Activity they belong to, so the immersive setting of dialogFragment and Dialog changes the properties in your own window instead of changing the properties in the Actvity window .
  • Close and destroy: Execute in the activity's onDestroy method, because mImmersionBarMap stores the ZanImmersionBar object corresponding to each Activity, so when the Activity is closed, it needs to be released in time, otherwise there will be too many useless ZanImmersionBar objects in mImmersionBarMap.
  ZanImmersionBar.with(this).destroy(); //必须调用该方法,防止内存泄漏
   public void destroy() {
          //取消监听
          cancelListener();
          //删除当前界面对应的ImmersionBar对象
          Iterator<Map.Entry<String, ZanImmersionBar>> iterator = mImmersionBarMap.entrySet().iterator();
          while (iterator.hasNext()) {
              Map.Entry<String, ZanImmersionBar> entry = iterator.next();
              if (entry.getKey().contains(mImmersionBarName) || (entry.getKey().equals(mImmersionBarName))) {
                  iterator.remove();
              }
          }
      }

2.1.2 Initialize the status bar and navigation bar

​ This method is to initialize the parameters of the previous step, and the initialization process will be differentiated according to the three stages of immersion and different manufacturers. It should be noted that the Xiaomi mobile phone system has its own customized settings, so partition settings are required

private void setBar() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !OSUtils.isEMUI3_x()) {
            //适配刘海屏
            fitsNotchScreen();
            //初始化5.0以上,包含5.0
            uiFlags = initBarAboveLOLLIPOP(uiFlags);
            //android 6.0以上设置状态栏字体为暗色
            uiFlags = setStatusBarDarkFont(uiFlags);
            //android 8.0以上设置导航栏图标为暗色
            uiFlags = setNavigationIconDark(uiFlags);
        } else {
            //初始化5.0以下,4.4以上沉浸式
            initBarBelowLOLLIPOP();
        }
             ...    
    }
    if (OSUtils.isMIUI6Later()) {
        //修改miui状态栏字体颜色
        setMIUIBarDark(mWindow, MIUI_STATUS_BAR_DARK, mBarParams.statusBarDarkFont);
        //修改miui导航栏图标为黑色
        if (mBarParams.navigationBarEnable) {
            setMIUIBarDark(mWindow, MIUI_NAVIGATION_BAR_DARK, mBarParams.navigationBarDarkIcon);
        }
    }
    ...
}

We can focus on the status bar and navigation bar initialization above 5.0, set the initial window properties, and then set the navigation bar and status bar color

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int initBarAboveLOLLIPOP(int uiFlags) {
    //Activity全屏显示,但状态栏不会被隐藏覆盖,状态栏依然可见,Activity顶端布局部分会被状态栏遮住。
    uiFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
    mWindow.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    //判断是否存在导航栏
    if (mBarConfig.hasNavigationBar()) {
        mWindow.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }
    //需要设置这个才能设置状态栏和导航栏颜色
    mWindow.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    //设置状态栏颜色
    if (mBarParams.statusBarColorEnabled) {
        mWindow.setStatusBarColor(ColorUtils.blendARGB(mBarParams.statusBarColor,
                mBarParams.statusBarColorTransform, mBarParams.statusBarAlpha));
    } else {
        mWindow.setStatusBarColor(ColorUtils.blendARGB(mBarParams.statusBarColor,
                Color.TRANSPARENT, mBarParams.statusBarAlpha));
    }
      ...
    return uiFlags;
}

Through code analysis, it can be seen that what ZanImmersionBar actually does is to split the immersive method of setting up the steps and increase the setting of personality attributes, and distinguish the three stages of immersion from different manufacturers to distinguish independent method setting calls.

2.2 Recommendations and use

  • It is recommended to initialize and destroy in BaseActivity
    public class BaseActivity extends AppCompatActivity {
  
         @Override
         protected void onCreate(@Nullable Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             // 所有子类都将继承这些相同的属性,请在设置界面之后设置
             ZanImmersionBar.with(this).init();  
         }
         @Override
         protected void onDestroy() {
             super.onDestroy();
             // 必须调用该方法,防止内存泄漏
             ZanImmersionBar.with(this).destroy();  
         }
     }

  • Show the effect of using in Activity
    image

2.3 Use ZanImmersionBar in Fragment

Note that using ZanImmersionBar in Fragment requires initializing ZanImmersionBar in the carried Activity, otherwise an exception will be thrown

    public abstract class BaseFragment{
         @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
             super.onViewCreated(view, savedInstanceState);
             initImmersionBar();
    }
         @Override
       public void initImmersionBar() {
            ZanImmersionBar.with(this).keyboardEnable(true).init();
        }
    }

The specific Fragment calls the following methods:

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ZanImmersionBar.with(this)
                .statusBarDarkFont(true)
                .statusBarColor(R.color.btn1)
                .navigationBarColor(R.color.btn1)
                .init();
    }

  • Set Fragment's status bar color and status bar font color effect
    image

2.4 Implement immersion in Dialog

The way to set ZanImmersionBar in Dialog is the same as in Fragment or Activity. If there are settings in Fragment or Activity and the dialog appears and the status bar does not need to be changed, there is no need to set ZanImmersionBar. If you need to customize the above advanced usage, it is also supported in Dialog

  • Used in conjunction with dialogFragment
      ZanImmersionBar.with(this).init();

  • Other dialog
      ZanImmersionBar.with(this, dialog).init();

image

2.5 Implementing immersive style in PopupWindow

The focus is to call the following method, but this method will cause the bottom layout of the mobile phone with a navigation bar to be covered by the navigation bar, and the bottom input box cannot pop up according to the soft keyboard pop-up. This attribute needs to be used when the pop-up at the top, if it is the bottom pop-up box, it depends on the situation.

    popupWindow.setClippingEnabled(false);

2.6 The status bar overlaps the top of the layout solution, choose one of the six options (optional)

Normal use of ZanImmersionBar generally does not need to consider the overlap problem, but the ZanImmersionBar is connected to the project and the page does not consider the height of the status bar reserved for the head control, and the page content needs to be immersed in the status bar or customized status bar. In this case, the overlap problem needs to be considered . When talking about the Android 4.4 version, there is one way to solve the overlap. You can also refer to several ways to solve the overlap problem of the status bar and the top of the layout.

  • ① Use dimen to customize the height of the status bar, it is not recommended, because the height of the device status bar is not fixed

Under the values-v19/dimens.xml file

        <dimen name="status_bar_height">25dp</dimen>

Under the values/dimens.xml file

        <dimen name="status_bar_height">0dp</dimen>

Then add the view tag in the layout interface, and specify the height as status bar height

       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:app="http://schemas.android.com/apk/res-auto"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:background="@color/darker_gray"
           android:orientation="vertical">
       
           <View
               android:layout_width="match_parent"
               android:layout_height="@dimen/status_bar_height"
               android:background="@color/colorPrimary" />
       
           <android.support.v7.widget.Toolbar
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:background="@color/colorPrimary"
               app:title="方法一"
               app:titleTextColor="@android:color/white" />
       </LinearLayout>

  • ② Use the fitsSystemWindows property of the system, using this property will not cause the input box to conflict with the soft keyboard, do not use this property in Fragment
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:orientation="vertical"
           android:fitsSystemWindows="true">
       </LinearLayout>

Then you must specify the status bar color when using ImmersionBar

       ZanImmersionBar.with(this)
            .statusBarColor(R.color.colorPrimary)
            .init();

Note: ZanImmersionBar must be used after setting the layout

  • ③ Use the fitsSystemWindows(boolean fits) method of ZanImmersionBar
        ZanImmersionBar.with(this)
            .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
            .statusBarColor(R.color.colorPrimary)
            .init();

  • ④ Use the statusBarView(View view) method of ZanImmersionBar

Add View tag above the title bar, and specify the height as 0dp

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
               xmlns:app="http://schemas.android.com/apk/res-auto"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="@color/darker_gray"
               android:orientation="vertical">
           
               <View
                   android:layout_width="match_parent"
                   android:layout_height="0dp"
                   android:background="@color/colorPrimary" />
           
               <android.support.v7.widget.Toolbar
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"
                   android:background="@color/colorPrimary"
                   app:title="方法四"
                   app:titleTextColor="@android:color/white" />
        </LinearLayout>

Then use the statusBarView method of ZanImmersionBar and specify the view.

         ZanImmersionBar.with(this)
               .statusBarView(view)
               .init();
         //或者
         //ZanImmersionBar.setStatusBarView(this,view);

  • ⑤ Use the titleBar (View view) method of ZanImmersionBar, the principle is to set paddingTop
             ZanImmersionBar.with(this)
                   .titleBar(view) //可以为任意view,如果是自定义xml实现标题栏的话,最外层节点不能为RelativeLayout
                   .init();
             //或者
             //ZanImmersionBar.setTitleBar(this, view);

  • ⑥ Use the titleBarMarginTop(View view) method of ZanImmersionBar, the principle is to set marginTop
             ZanImmersionBar.with(this)
                   .titleBarMarginTop(view)  //可以为任意view
                   .statusBarColor(R.color.colorPrimary)  //指定状态栏颜色,根据情况是否设置
                   .init();
             //或者使用静态方法设置
             //ZanImmersionBar.setTitleBarMarginTop(this,view);

to sum up

When dealing with the Android immersive status bar and navigation bar, it will be very big, and will not understand the FLAG attributes of the relevant settings of the window. If you want to distinguish the general meaning of these attributes, you need to unpack it from the background. First, get familiar with the immersive appearance. What can and can’t be done with the attributes and versions of the three stages, and then understand which version of the attributes customized by each manufacturer is used, and whether it needs to be adapted to the special-shaped screen, and finally the actual development and requirements Status bar and navigation bar processing. However, after Android 6.0, the customization status of manufacturers has become more and more meaningless. In the future, the native trend of Android will also make developers more and more comfortable using immersion.

Guess you like

Origin blog.csdn.net/YZcoder/article/details/101059241