说明
沉浸式状态栏主要指的是当app的actionbar部分是一个图片或者是纯色的背景时,状态栏和ActionBar联合起来的这样一种效果。
首先去掉actionbar的位置,指定主题:
android:theme=”@style/Theme.AppCompat.Light.NoActionBar”
但是这时在5.0以上的机器状态栏会显示灰色:
在4.4的机器中会显示黑色,如下图:
创建沉浸式状态栏
在网上大约有三种方式来创建:
- 使用主题文件(xml)
- 重写onWindowFocusChanged方法
在res文件夹下新建两个文件夹v19和v21也就是4.4和5.0之后的样式,参见天气
然后在要设置沉浸式布局的根目录添加如下属性:
android:background=”@drawable/bg”
android:fitsSystemWindows=”true”
对应的跟布局文件:
<android.support.constraint.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"
tools:context="haotinayi.win.myapplication.MainActivity"
android:background="@drawable/bg"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
styles.xml(v19)
<resources>
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
</resources>
在4.4上的效果:
styles.xml(v21)
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">true</item>
<!--Android 5.x开始需要把颜色设置透明,否则导航栏会呈现系统默认的浅灰色-->
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
注意,两者的android:windowTranslucentStatus状态值不同
重写方法设置状态栏
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && Build.VERSION.SDK_INT >= 19) {
View decorView = getWindow().getDecorView();
int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
//需要api在21以上
getWindow().setNavigationBarColor(Color.TRANSPARENT);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
}
不用指定主题,不用指定属性android:fitsSystemWindows="true"