定义一个适配沉浸式状态栏 的 TitleBar

第一步,定义一个TitleBar

我使用自定义 FrameLayout 后inflate一个布局的方式来静态的使用一个写好的布局,免去手写布局的麻烦

public class TitleBar extends FrameLayout {
LayoutInflater.from(context).inflate(R.layout.myview_title_bar, this);//直接改变布局,从而静态的使用子控件\

第二步,使用沉浸状态栏后测试效果

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="#F00"
    android:orientation="vertical">

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/blue"
        android:fitsSystemWindows="true"
        app:title_text="标题栏" />

            android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="#FF0"
        android:text="主体内容\n第二行\n第三行\n第四行" />

            android:layout_width="match_parent"
        android:layout_height="wrap_content" />

测试页面是这个样子:

定义一个适配沉浸式状态栏 的 TitleBar_第1张图片顶部标题栏TextView、输入框、背景

看到标题栏是白色的,是因为标题栏是蓝色的FrameLayout中嵌套的TitleBar布局是白色的。

实际运行效果:

定义一个适配沉浸式状态栏 的 TitleBar_第2张图片

发现顶部状态栏变成了蓝色,看来这是自定义TitleBar的问题,fitsSystemWindows属性让TitleBar的paddingTop增加了一个状态栏高度,但由于TitleBar的子View高度固定了,导致TitleBar本身的蓝色漏出来。若要避免这种情况可以1、将TitleBar子View的高度固定为撑满,而TitleBar高度设为固定,2、将TitleBar的背景色设为同子View的颜色。3、改为给TItleBar子View设置fitsSystemWindows属性。

你可能感兴趣的:(定义一个适配沉浸式状态栏 的 TitleBar)