android狀態欄顏色修改
狀態欄顏色的修改在4.4和5.x環境下分別有不同的方式,低於4.4以下是不能修改的。
5.x環境下
方式一,狀態欄將顯示為純凈的顏色,沒有漸變效果
- /**
- * 狀態欄相關工具類
- *
- */
- public class StatusBarUtils {
- public static void setWindowStatusBarColor(Activity activity, int colorResId) {
- try {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- Window window = activity.getWindow();
- window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
- window.setStatusBarColor(activity.getResources().getColor(colorResId));
- //底部導航欄
- //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void setWindowStatusBarColor(Dialog dialog, int colorResId) {
- try {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- Window window = dialog.getWindow();
- window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
- window.setStatusBarColor(dialog.getContext().getResources().getColor(colorResId));
- //底部導航欄
- //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
效果圖如下:狀態欄被改成android.R.color.holo_blue_bright,標題欄顏色可以和狀態欄一樣,EditText的輸入也沒有受影響


ps:如果頂部為漸變效果,可能是在主題中設置
windowTranslucentStatus=true
屬性。
方式二:
通過Style來修改狀態欄顏色。
1.設置 colorPrimary,colorPrimaryDark兩個顏色。
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@android:color/holo_blue_bright</item>
<item name="colorPrimaryDark">@android:color/holo_blue_bright</item>
</style>
2. AndroidManifest.xml文件中的targetSdkVersion必須設置在
21以上。
3.parent主題必須是
Theme.AppCompat開頭,兼容包下的主題,所以必須一用
v7包。
colorPrimary,colorPrimaryDark這兩個屬性是Material Design風格中規定的。具體位置如下圖所示:

方式三:
1.在res/values-v19文件夾下添加styles.xml文件內容如下
<style name="AppTheme" parent="@style/BaseAppTheme">
<item name="android:windowTranslucentStatus">true</item>
</style>
2.頂部標題的控件設置兩個屬性
android:background="@android:color/holo_blue_bright"
android:fitsSystemWindows="true"
則狀態欄會保持與設置fitsSystemWindow屬性的控件的背景顏色一致。
4.4環境下
上面的方式三也適用4.4環境。不過4.4和5.x下顯示的效果有差異。根據本人測試結果來看,不同的手機廠商對於這種情況下,狀態欄有的是漸變,有的是添加了一層黑色半透明層。
存在bug及解決辦法
修改windowTranslucentStatus/Navigation="true"。會導致EditText輸入時,即使使用了 adjustResize,軟鍵盤也會擋住EditText
解決辦法參考:
其他參考資料: