美文网首页
fitSystemWindow的用法

fitSystemWindow的用法

作者: 素颜的你 | 来源:发表于2018-05-02 20:55 被阅读0次

最近在研究沉浸式状态栏,fitSystemtWindow在沉浸式状态栏中发挥重要作用,网上介绍的真的很混乱。在此,将亲身实践总结一下,供大家参考


fitSystemWindow是什么

设置应用布局时是否考虑系统窗口布局;如果为true,将调整系统窗口布局以适应你自定义的布局。

fitSystemWindow生效条件

  • android:fitSystemWindow属性,只有在 sdk>=19,即系统版本大于等于4.4才会生效。
  • 只有在设置了StatusBar或者NavigationBar为透明时生效

使用方法

1、设置状态栏透明方法(StatusBar透明)

在设置activity主题添加下边的属性:
<item name="android:windowTranslucentStatus">true</item>

或者在java代码中设置以下属性:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}

此时,fitSystemWindow设置为true时,控件的padding设置会失效,自动添加一个值等于状态栏高度的paddingTop
2、设置底部导航栏透明方法(NavigationBar透明)

在activity的主题中设置以下属性:
<item name="android:windowTranslucentNavigation">true</item>
//或者在代码中添加:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}

此时,android:fitsSystemWindows="true"属性的view会自动添加一个值等于导航栏高度的paddingBottom

具体操作例子

MainActivity.kt代码

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)//设置状态栏透明

        setContentView(R.layout.activity_main)
    }
}

布局文件activity_main代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:orientation="vertical"
    android:fitsSystemWindows="true"  //fitSystemWindow为true,对应下边第一张图
    android:fitsSystemWindows="false"  //fitSystemWindow为false,对应 下边 第二张图
    tools:context="com.baixin.statusbar.statusbaroperate.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="@android:color/darker_gray"
        android:gravity="center"
        android:text="标题" />
</LinearLayout>

运行效果如下,可以看出LinearLayout自动多出了一个Paddingtop,高度为StatusBar的高度:


image.png
image.png

相关文章

网友评论

      本文标题:fitSystemWindow的用法

      本文链接:https://www.haomeiwen.com/subject/peicrftx.html