Android沉浸式状态栏实现

来源:互联网 发布:java中复制文件夹 编辑:程序博客网 时间:2024/05/20 06:06

Step1:状态栏与导航栏半透明化

  • 方法一:继承主题特定主题
    在Android API 19以上可以使用****.TranslucentDecor***有关的主题,自带相应半透明效果
    例如:

    <style name="FullBleedTheme" parent="android:Theme.Holo.Light.NoActionBar.TranslucentDecor">    <!-- API 19 theme customizations can go here. --></style>
  • 方法二:自定义主题中使用一下设置

    <item name="android:windowTranslucentStatus" tools:targetApi="kitkat">true</item><item name="android:windowTranslucentNavigation" tools:targetApi="kitkat">true</item>
  • 方法三:在Activity中设置布局文件之后调用这些代码实现

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {Window window = getWindow();// Translucent status barwindow.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// Translucent navigation barwindow.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);}

    SystemBarTint作者提供的变形方法如下

    @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);}

Step2:此时状态栏占有的位置消失,方法同样有三

  • 方法一:需要在布局文件根布局中添加一下代码

    android:fitsSystemWindows="true"
  • 方法二:在主题中设置如下:

    <item name="android:fitsSystemWindows">true</item>
  • 方法三:使用Java代码:

    rootview.setFitsSystemWindows(true);

Step3:设定状态栏和导航栏背景色

这时候状态栏半透明,显示的颜色根据根布局的背景颜色而来,由此可以给根布局背景色位所需的颜色即可。
但是这样会给根布局的子布局控件的背景设置带来不便。
所以采用SystemBarTint实现沉浸式状态栏
方法如下:

SystemBarTintManager tintManager = new SystemBarTintManager(this);            tintManager.setStatusBarTintEnabled(true);            tintManager.setNavigationBarTintEnabled(true);            tintManager.setTintColor(ContextCompat.getColor(this, R.color.colorPrimary));

几个问题

  • 使用SystemBarTint不能给状态栏设置多个颜色,不能自动取色?
  • Android5.0(API 21)之后ActionBar主题中几个颜色代表的意义

      <style name="AppTheme" parent="android:Theme.Material"><!-- Main theme colors --><!--   your app branding color for the app bar --><item name="android:colorPrimary">@color/primary</item><!--   darker variant for the status bar and contextual app bars --><item name="android:colorPrimaryDark">@color/primary_dark</item><!--   theme UI controls like checkboxes and text fields --><item name="android:colorAccent">@color/accent</item>  </style>
  • 定制配色工具
    (来自Android官方文档)

0 0
原创粉丝点击