開發中,設計圖照着蘋果來的(/(ㄒoㄒ)/~~),導航欄顏色的設置直接影響美觀和用戶體驗,kitkat4.4及其以下版本先不管,4.4以上版本還是很有希望實現的,且往下看。
準備工作:首先在res文件下新建一個values-v21文件夾,在該文件下新建一個style.xml文件,style.xml文件裏的所有屬性都是針對api21及其以上版本設置的。
設置頂部透明狀態欄:
<item name="android:windowTranslucentStatus">true</item>
看效果:
可以看到設置該屬性後,界面被拉伸到頂部。
如果想要代碼動態設置,效果一樣的:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
WindowManager.LayoutParams attributes = window.getAttributes();
attributes.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
window.setAttributes(attributes);
}
去除頂部灰色陰影:
android:windowTranslucentStatus 屬性並不能完美呈現出像ios應用的導航欄效果,頂部多了層灰色半透明陰影,如何去掉這個效果奈,看下面代碼:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.setStatusBarColor(Color.TRANSPARENT)
}
效果圖:
解決置頂問題:
上面的設置會導致佈局整體拉伸到狀態欄頂部,就像第一張圖一樣,這並不是我們想要的效果。如果能夠獲取狀態欄的高度,設置對應控件的paddingTop,問題不就可以解決了嘛。
1、獲取狀態欄高度
由於每個手機分辨率不一樣,狀態欄的高度肯定不能設置成一個固定值,只能動態獲取了:
public int getStatusBarHeight() {
int result = 0;
int resourceId = getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getContext().getResources().getDimensionPixelSize(resourceId);
}
return result;
}
2、動態設置paddingTop
final ViewGroup linear_bar = (ViewGroup) activity.findViewById(title_id); // 所需要設置控件
linear_bar.post(new Runnable() {
@Override
public void run() {
linear_bar.setPadding(0, getStatusBarHeight(activity), 0, 0);
}
});
效果圖:
設置底部導航欄透
明:
<item name="android:windowTranslucentNavigation">true</item>
效果圖:
代碼設置:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
WindowManager.LayoutParams attributes = window.getAttributes();
attributes.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
window.setAttributes(attributes);
}
關於源碼,請戳https://github.com/jjjSilence/jjjPlus ,在白天/ 夜晚切換裏面O(∩_∩)O