從Android 4.4 開始魁索,我們可以修改狀態(tài)欄的顏色。本文主要是總結(jié)下修改過程遇到的一些問題。
透明狀態(tài)欄
在values-v19
和values-v21
目錄下分別創(chuàng)建style.xml.在style.xml中添加AppBaseTheme:
<style name="MyBaseTheme"parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowTranslucentStatus">true</item>
</style>
其中<item name="android:windowTranslucentStatus">true</item>
則是將狀態(tài)欄透明荣赶,使我們的布局界面延伸到狀態(tài)欄。如圖:
很明顯上面的效果不是我們想要的鸽斟。除了標題欄頂?shù)搅藄tatusBar導(dǎo)致重疊了拔创,而且4.4和5.0+的顯示效果也不一樣。我們來看下規(guī)范的Material Design:
默認的md風(fēng)格是狀態(tài)欄應(yīng)該是20%透明的黑色(#33000000)富蓄。
首先解決第一個問題剩燥,要想不重疊我可以在布局文件中加上android:fitsSystemWindows="true"
或者添加一個和狀態(tài)欄高度相等的view。我這里用的是第二種方法立倍。實現(xiàn)一個自定義的View StatusBarPlaceHolder
:
public class StatusBarPlaceHolder extends RelativeLayout{
private int statusHeight;
public StatusBarPlaceHolder(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public StatusBarPlaceHolder(Context context) {
super(context);
init(context);
}
private void init(Context context){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
statusHeight = getStatusHeight(context);
}else {
statusHeight = 0;
}
}
private int getStatusHeight(Context context){
int result = 0;
int resultId = context.getResources().getIdentifier("status_bar_height","dimen","android");
if (resultId > 0){
result = context.getResources().getDimensionPixelOffset(resultId);
}
return result;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = MeasureSpec.makeMeasureSpec(statusHeight,MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, height);
}
}
添加上面的view到布局文件后運行效果如圖:
OK躏吊,看起來總算不那么難看了,下面解決第二個問題帐萎,讓4.4上的狀態(tài)欄盡量的貼近標準的md樣式,這里我用到了一個很好的第三方庫Android System Bar Tint
// create our manager instance after the content view is set
SystemBarTintManager manager = new SystemBarTintManager(this);
// enable status bar tint
manager.setStatusBarTintEnabled(true);
// set a custom tint color for all system bars
manager.setStatusBarTintColor(Color.parseColor("#33000000"));
再來看下效果:
差不多就這個樣子吧胜卤。
遇到的問題
這里在開發(fā)中遇到了一個問題疆导,就是在項目中用到了軟鍵盤,在透明了狀態(tài)欄之后android:windowSoftInputMode="adjustResize"
就失去效果了葛躏,editText就彈不起來了澈段。我這里用到的解決方案是在布局文件中加入android:fitsSystemWindows="true"
使布局文件在狀態(tài)欄之下悠菜。關(guān)于這個問題還可以參考其他的解決方案
Tips
- android:fitsSystemWindows="true"在一個Activity的界面中只能有1個
- 注意
android:fitsSystemWindows="true"
添加的位置,不要導(dǎo)致之前設(shè)置過的view被頂下來了败富。 - 當(dāng)然api 21以上可以也可以用
<item name="statusBarColor">@color/primary_dark</item>
來設(shè)置狀態(tài)欄顏色悔醋。
參考 :Demo源碼