Step1:狀態欄與導航欄半透明化
- 方法一:繼承主題特定主題
在Android API 19以上可以使用*.TranslucentDecor有關的主題,自帶相應半透明效果
例如:
<style name="FullBleedTheme" parent="android:Theme.Holo.Light.NoActionBar.TranslucentDecor">
<!-- API 19 theme customizations can go here. -->
</style>
- 方法二:自定義主題中使用一下設置
<item name="android:windowTranslucentStatus" tools:targetApi="kitkat">true</item>
<item name="android:windowTranslucentNavigation" tools:targetApi="kitkat">true</item>
- 方法三:在Activity中設置布局文件之后調用這些代碼實現
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
// Translucent status bar
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// Translucent navigation bar
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
SystemBarTint作者提供的變形方法如下
@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);
}
Step2:此時狀態欄占有的位置消失,方法同樣有三
- 方法一:需要在布局文件根布局中添加一下代碼
android:fitsSystemWindows="true"
- 方法二:在主題中設置如下:
<item name="android:fitsSystemWindows">true</item>
- 方法三:使用Java代碼:
rootview.setFitsSystemWindows(true);
Step3:設定狀態欄和導航欄背景色
這時候狀態欄半透明,顯示的顏色根據根布局的背景顏色而來,由此可以給根布局背景色位所需的顏色即可。
但是這樣會給根布局的子布局控件的背景設置帶來不便。
所以采用SystemBarTint實現沉浸式狀態欄
方法如下:
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setNavigationBarTintEnabled(true);
tintManager.setTintColor(ContextCompat.getColor(this, R.color.colorPrimary));
幾個問題
- 使用SystemBarTint不能給狀態欄設置多個顏色,不能自動取色?
- Android5.0(API 21)之后ActionBar主題中幾個顏色代表的意義
<style name="AppTheme" parent="android:Theme.Material">
<!-- Main theme colors -->
<!-- your app branding color for the app bar -->
<item name="android:colorPrimary">@color/primary</item>
<!-- darker variant for the status bar and contextual app bars -->
<item name="android:colorPrimaryDark">@color/primary_dark</item>
<!-- theme UI controls like checkboxes and text fields -->
<item name="android:colorAccent">@color/accent</item>
</style>