注:公司開發任務適配是在4.4版本之上進行,所以此適配僅在4.4之上進行測試。
1、主要使用了第三方的開源項目SystemBarTint,github:https://github.com/jgilfelt/SystemBarTint
2、根據SystemBarTint自帶sample進行研究,主要步驟如下:
- 在Activity中加入如下代碼:
public class MainActivity extends BaseActivity { @Override public void setContentView() { setContentView(R.layout.activity_main); // 沉浸式狀態欄 setTranslucentStatus(); }
} /** * 為xml 的根布局添加android:fitsSystemWindows=”true” 屬性<br/> */ protected void setTranslucentStatus() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } SystemBarTintManager tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintEnabled(true); tintManager.setStatusBarTintResource(R.color.statusbar_bg);// 通知欄所需顏色 } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); }
注:有些資料說setTranslucentStatus()方法需要放在setConentView()之后,實際上沒有影響。
2. 在MainActivity的根布局中添加:
android:fitsSystemWindows="true"
3. 如果我們在布局中間加入一個自定義TextView控件,並且設置的背景色和setTranslucentStatus()方法中的color一樣的話,我們運行會發現效果如下圖:
其中,在statusbar與textview中間會有一個空白,這個空白是actionbar的留白,所以,如果使用自帶titlebar的話,要取消actionbar的顯示;如果使用actionbar的話,要將actionbar的背景設置為相同色。
public class MainActivity { @Override public void setContentView() { noTitleBar(); setContentView(R.layout.activity_main); // 沉浸式狀態欄 setTranslucentStatus(); } /** * 不顯示標題欄 */ protected void noTitleBar() { this.requestWindowFeature(Window.FEATURE_NO_TITLE); } }
效果如下:
4. 由於github上面的代碼是基於gradle的,下面放出基於eclipse的版本源碼。