版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39397471/article/details/77241129
开篇:
最近在独立的开发中遇到了Android状态栏的很多坑,在网上查了些资料也是众说纷纭,因此总结了一些网上的关于状态栏的知识点,用于在以后的开发中少踩些坑;
1. 不显示状态栏
不显示状态栏一般用于对屏幕空间要求较大时,比如欢迎界面,视频,横屏等;
不显示状态栏的方式有两种:
第一种方法:
在活动中中添加:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
第二种方法:
(Android5.0及以上的系统才支持)
if(Build.VERSION.SDK_INT >= 21){
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_main);
...
2. 设置状态栏为透明
第一种方法:
(Android4.4及以上的系统才支持)
在Style文件中添加代码:
<item name="android:windowTranslucentStatus">true</item>
由于是4.4版本才开始支持,因此需要做区分版本号处理:
第二种方法:
通过代码来指定:
public static void setStatusBarTransparent(Activity activity) {
Window window = activity.getWindow();
if (window != null) {
WindowManager.LayoutParams winParams = window.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
winParams.flags |= bits;
window.setAttributes(winParams);
}
}
3. 使用fitsSystemWindow属性:
android:fitsSystemWindows属性可以让设置的布局跳过系统状态栏的高度;
使用: 在根布局中配置xml属性:
android:fitsSystemWindows="true"
4. 设置状态栏颜色
在状态栏不透明情况下,改变状态栏的颜色;
(Android5.0及以上版本)
在style文件中设置颜色:(使用colorPrimaryDark属性改变颜色)
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@android:color/holo_green_light</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
使用该方法设置状态栏颜色,是改变系统默认的颜色,可能导致其他布局的颜色的改变,慎用;
使用代码动态设置:
public static void setStatusBarColor(Activity activity, int colorId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
if (window != null) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(activity.getResources().getColor(colorId));
}
}
}