android狀態欄顏色修改

android狀態欄顏色修改
 
狀態欄顏色的修改在4.4和5.x環境下分別有不一樣的方式,低於4.4如下是不能修改的。
 

5.x環境下html

方式一,狀態欄將顯示爲純淨的顏色,沒有漸變效果
/**
 * 狀態欄相關工具類
 *
 */
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兩個顏色。
<stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar">
     <itemname="colorPrimary">@android:color/holo_blue_bright</item>
     <itemname="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文件內容以下
<stylename="AppTheme"parent="@style/BaseAppTheme">
    <itemname="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
解決辦法參考:

 
其餘參考資料:

相關文章
相關標籤/搜索