设置沉浸式状态栏

在Android4.4之后推出了沉浸式状态栏,那么怎么使用它呢?下面我来讲解:

1、实现原理
沉浸式状态栏是在Google在4.4系统出来之后推出的,也就是说只能在4.4系统之上使用这个特性首先,我们要明白的是Activity的底层的布局是什么,是DecorView,也就是只要我们改变底层的DecorView的状态栏的背景就可以了。
2、实现方法
这里介绍一个GitHub上的开源库,用来实现改变的StatusBar的背景。
项目地址:SystemBarTint
具体的可以参考项目介绍。
3、具体的实现方法
(1)代码设置

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //首先检测当前的版本是否是api>=19的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            setTranslucentStatus(true);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(Color.parseColor("#FFC1E0"));
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on)
    {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on)
        {
            winParams.flags |= bits;
        }
        else
        {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}

(2)布局设置

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              <!--这两行是必须设置的-->
              android:fitsSystemWindows="true"
              android:clipToPadding="true"

              android:orientation="vertical"
              android:background="#FFD9EC"
        >

    <TextView
            android:text="沉浸式状态栏"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:textSize="23dp"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:background="#FFD9EC"
            />
    <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/darker_gray"/>

</LinearLayout>

你可能感兴趣的:(android,StatusBar,沉浸式,沉浸式状态栏)