第一步:
首先得讓你的activity的布局文件的根布局有android:fitsSystemWindows="true"
該屬性誉简,它指定了狀態(tài)欄占有一定的位子.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
android:fitsSystemWindows="true">
第二步:
在你的activity的onCreate
方法中調(diào)用該方法:
@TargetApi(19)
private void initWindow() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
View mStatusBarTintView = new View(this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, getStatusBarHeight());
params.gravity = Gravity.TOP;
mStatusBarTintView.setLayoutParams(params);
mStatusBarTintView.setBackgroundColor(getResources().getColor(DEFAULT_TINT_COLOR));
mStatusBarTintView.setVisibility(View.VISIBLE);
decorView.addView(mStatusBarTintView);
}
}
protected int getStatusBarHeight(){
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, sbar = 38;//默認為38,貌似大部分是這樣的
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
sbar = getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return sbar;
}
這里獲取狀態(tài)欄的獲取就不說了,上一篇文章已經(jīng)說過了關于如何獲取android狀態(tài)欄高度,上面的DEFAULT_TINT_COLOR
就是你要指定的狀態(tài)欄顏色值,我這里設置的顏色值跟toolbar的顏色一樣榨婆。