首先创建一个BaseActivity或者BaseFragment,
后面需要沉浸式状态的继承BaseActivity或BaseFragment,
然后在XML文件中添加想设置的状态栏背景颜色,以下两句代码
android:background="#1677FE"
android:fitsSystemWindows=“true”
BaseActivity代码如下:
abstract class BaseActivity:AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREENor View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)window.statusBarColor = Color.TRANSPARENT} else {window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) //隐藏状态栏}onCreateActivity(savedInstanceState)}abstract fun onCreateActivity(savedInstanceState: Bundle?)
}
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#1677FE"android:fitsSystemWindows="true"tools:context=".MainActivity"><androidx.appcompat.widget.Toolbarandroid:layout_width="match_parent"android:layout_height="wrap_content"app:title="标题"android:background="#eeeeee"app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
实现效果:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#1677FE"tools:context=".MainActivity"><androidx.appcompat.widget.Toolbarandroid:layout_width="match_parent"android:layout_height="wrap_content"app:title="标题"android:fitsSystemWindows="true"android:background="#eeeeee"app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
实现效果: