沉浸式状态栏是根据很多朋友的文章总结出来的,看的太多所以找不到出处了,十分抱歉,现在只是把这些代码从我的项目中拿出来做个记录。
- Android5.0之后,状态栏颜色可直接设置
- Android4.4至5.0,根据Activity找到android.R.content,在其中添加一个View(高度为statusbarHeight)
在super.onCreate(savedInstanceState)后加入此代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
//需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// 设置状态栏颜色
window.setStatusBarColor(getResources().getColor(R.color.state_bar_default));
ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
View mChildView = mContentView.getChildAt(0);
if (mChildView != null) {
//注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
ViewCompat.setFitsSystemWindows(mChildView, false);
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
ViewGroup mContentParent = (ViewGroup) mContentView.getParent();
View statusBarView = mContentParent.getChildAt(0);
if (statusBarView != null && statusBarView.getLayoutParams() != null && statusBarView.getLayoutParams().height == getStatusHeight()) {
//避免重复调用时多次添加View
statusBarView.setBackgroundColor(getResources().getColor(R.color.state_bar_default));
return;
}
//创建一个假的 View, 并添加到 ContentParent
statusBarView = new View(this);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusHeight());
statusBarView.setBackgroundColor(getResources().getColor(R.color.state_bar_default));
mContentParent.addView(statusBarView, 0, lp);
//ChildView 不预留空间
View mChildView = mContentParent.getChildAt(0);
if (mChildView != null) {
ViewCompat.setFitsSystemWindows(mChildView, false);
}
}
获取状态栏高度
private int getStatusHeight() {
int statusHeight = 0;
Rect localRect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
statusHeight = localRect.top;
if (statusHeight == 0) {
Class<?> localClass;
try {
localClass = Class.forName("com.android.internal.R$dimen");
Object localObject = localClass.newInstance();
int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
statusHeight = getResources().getDimensionPixelSize(i5);
} catch (Exception e) {
e.printStackTrace();
}
}
return statusHeight;
}