天天看點

實作Android狀态欄變色(純色或者漸變色)實作Android狀态欄變色(純色或者漸變色)

實作Android狀态欄變色(純色或者漸變色)

Android開發中為了保證顯示一緻性,可能需要調整statusBar的背景色。Android 5.0開始隻需要修改styles.xml檔案中colorPrimaryDark的顔色值就可以修改statusbar背景色。但是colorPrimaryDark隻能設定固定色值的顔色,而且設定主題的話也是統一所有頁面的statusbar都是一樣的,要是某單一頁面要單獨設定statusbar背景色又要在styles.xml重複寫然後設定,有點麻煩,而且最關鍵的是無法設定漸變色。

這樣的話我們可以在activity的基類BaseActivity中增加統一的代碼:

/**
     * 修改狀态欄顔色,支援5.0以上版本
     */
    public static void setStatusBarColor(Activity activity, int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(activity.getResources().getColor(colorId));
        }

    }
           

如果某一個頁面需要單獨設定StatusBar的話,在onCreate()方法中直接調用上面的方法,把顔色值傳進去就OK了。

上面說的是單一顔色的,現在說說漸變顔色的,漸變顔色的話我們一般是在drawable檔案夾裡面建一個shape的資源檔案,可能會有多種顔色,是以上面的方法顯然不合适了,看下面:

//改變狀态欄顔色
    private void setThisStatusBarColor() {
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                initStatusBar();
                getWindow().getDecorView().removeOnLayoutChangeListener(this);
            }
        });

    }

    private void initStatusBar() {
        //利用反射機制修改狀态欄背景
        int identifier = getResources().getIdentifier("statusBarBackground", "id", "android");
        View statusBarView = getWindow().findViewById(identifier);
        statusBarView.setBackgroundResource(R.drawable.shape_bg_gradient_blue_no_corner);
    }
           

最後面傳入自己寫好的drawable資源檔案(我這裡是R.drawable.shape_bg_gradient_blue_no_corner),畢竟需要的顔色不一樣,哪個頁面需要調用就好了。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- 漸變 預設從左到右, angle: 270表示從上到下,180表示從右到左 -->
    <gradient
        android:endColor="#AF76EB"
        android:startColor="#7D76E1" />
</shape>
           

注:上面的方法隻對Android5.0以上有效,4.4以下的還需求适配的話自己網上看看其他的部落格吧,畢竟現在市場上的手機很少有4.4以下的了。