一、系统的方式沉浸式状态栏实现
1.0在代码中加入以下方法
/**
* 沉浸式状态栏
*/
private void initState() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// 透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
2布局文件中
android:clipToPadding=”true”
android:fitsSystemWindows=”true”
效果
二、布局文件中添加隐藏布局,然后通过反射来获取状态栏的高度,然后把这个高度设置成这个隐藏的布局的高度
1布局文件中添加隐藏的布局
<LinearLayout
android:id="@+id/ll_bar"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/orange"
android:orientation="vertical"
android:visibility="gone" >
</LinearLayout>
2.代码中获取状态栏高度,并赋值给隐藏的布局
@SuppressLint(“InlinedApi”)
private void initState() {
//当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&Build.VERSION.SDK_INT <Build.VERSION_CODES.LOLLIPOP) {
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//
LinearLayout linear_bar = (LinearLayout) findViewById(R.id.ll_bar);
linear_bar.setVisibility(View.VISIBLE);
//获取到状态栏的高度
int statusHeight = getStatusBarHeight();
//动态的设置隐藏布局的高度
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linear_bar.getLayoutParams();
params.height = statusHeight;
linear_bar.setLayoutParams(params);
}
}
/**
* 通过反射的方式获取状态栏高度
*
* @return
*/
private int getStatusBarHeight() {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
return getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
三、使用第三方库
1.库地址:https://github.com/jgilfelt/SystemBarTint
2.依赖:
compile ‘com.readystatesoftware.systembartint:systembartint:1.0.3’
3布局文件中加入
android:fitsSystemWindows=”true”
android:clipToPadding=”true
4代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
// 激活状态栏
tintManager.setStatusBarTintEnabled(true);
// enable navigation bar tint 激活导航栏
tintManager.setNavigationBarTintEnabled(true);
//设置系统栏设置颜色
//tintManager.setTintColor(R.color.red);
//给状态栏设置颜色
tintManager.setStatusBarTintResource(R.color.mask_tags_1);
//Apply the specified drawable or color resource to the system navigation bar.
//给导航栏设置资源
tintManager.setNavigationBarTintResource(R.color.mask_tags_1);
}