關于沉浸式狀態欄相信大家都不陌生,IOS系統很早就有,android5.0及以后版本都支持給狀態欄著色,而目前android主流版本還是4.4,網上通用實現4.4(API19)沉浸式狀態欄也都是依賴于可以將狀態欄變為透明的屬性,再為其著色,主要實現代碼:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);? ? ? ? setContentView(R.layout.activity_match_actionbar);//只對api19以上版本有效if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {? ? ? ? ? ? setTranslucentStatus(true);? ? ? ? }//為狀態欄著色SystemBarTintManager tintManager =newSystemBarTintManager(this);? ? ? ? tintManager.setStatusBarTintEnabled(true);? ? ? ? tintManager.setStatusBarTintResource(R.color.statusbar_bg);? ? }@TargetApi(19)privatevoidsetTranslucentStatus(booleanon){? ? ? ? Window win = getWindow();? ? ? ? WindowManager.LayoutParams winParams = win.getAttributes();finalintbits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;if(on) {? ? ? ? ? ? winParams.flags |= bits;? ? ? ? }else{? ? ? ? ? ? winParams.flags &= ~bits;? ? ? ? }? ? ? ? win.setAttributes(winParams);? ? }
再在根布局添加以下兩個屬性:
android:fitsSystemWindows="true"android:clipToPadding="false"
這樣就可以了,以上著色使用了SystemBarTint。
為什么我要尋找其他的方案?
面對大多數的界面自然是沒有多大問題,但是針對類似QQ這種側滑的界面,如圖:
Screenshot_2015-12-30-09-55-33.png
我的手機系統版本是4.4的,如果想做成QQ側滑背景這樣的效果,使用上面的方案就變成了這樣
Screenshot_2015-12-30-09-55-34.png
這樣出來的效果就會很丑,于是才有了改進版的方案,不知QQ是否是這樣做的。
除了上述的缺陷以外,還有一點看著不是很舒服,就是當我使用抽屜菜單或者滑動返回效果的時候是這樣的
狀態欄并沒有陰影效果
我想要的效果是這樣的
狀態欄也會跟著一起滑動
第一種思路
自定義一個狀態欄,不能添加“ android:fitsSystemWindows="true"
”這個屬性,不然無法填充到狀態欄,如下
在到代碼中判斷
@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);? ? ? ? View statusBar = findViewById(R.id.status_bar);? ? ? ? setContentView(R.layout.activity_test);//判斷SDK版本是否大于等于19,大于就讓他顯示,小于就要隱藏,不然低版本會多出來一個if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {? ? ? ? ? ? setTranslucentStatus(true);? ? ? ? ? ? statusBar.setVisibility(View.VISIBLE);//還有設置View的高度,因為每個型號的手機狀態欄高度都不相同}else{? ? ? ? ? ? statusBar.setVisibility(View.GONE);? ? ? ? }? ? }@TargetApi(19)privatevoidsetTranslucentStatus(booleanon){? ? ? ? Window win = getWindow();? ? ? ? WindowManager.LayoutParams winParams = win.getAttributes();finalintbits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;if(on) {? ? ? ? ? ? winParams.flags |= bits;? ? ? ? }else{? ? ? ? ? ? winParams.flags &= ~bits;? ? ? ? }? ? ? ? win.setAttributes(winParams);? ? }
其實,這樣已經解決了我上面提出的兩個問題
第二種實現方案
第二種方案是為了解決第一種方案中遇到的奇葩問題,設置了透明屬性的界面(聊天及底下評論的框框)不能被系統輸入法頂上去,之前寫過一篇Android 聊天界面背景圖片被輸入法“頂上去”問題解析,現在遇到的就是無論如何聊天的輸入框都不能被系統輸入法頂上去(就是打字看不到輸入框),經過一番測試,發現竟然和“ android:fitsSystemWindows="true"
”這個屬性有關,加上去輸入框就沒問題,但自定義的狀態欄不能被填充到真正的狀態欄位置
未標題-1.png
陷入了兩難的境地,加還是不加都有問題,而且都特別明顯,說了半天,來看看第二種方案。
關鍵在于下面兩個屬性,還有需要在其他子布局添加背景,不然就跟隨了最外層的背景,代碼部分還是采用網上通用方案,只是不需要自定義的狀態欄了,也不需要計算狀態欄的高度
android:fitsSystemWindows="true"android:background="@android:color/holo_green_light"
最終效果
源碼下載:StatusBarDemo