Android 沉浸式狀態欄完美解決方案

原文鏈接:https://blog.csdn.net/u014418171/article/details/81223681

 

本文爲轉載文章,左上有原文鏈接

我跟原文作者一樣,也找了很多亂七八糟的文章,本人特別討厭那種浪費時間的半成品文章或demo,轉載之前我已經完美的實現了我想要的效果,在這裏轉發,希望更多需要的夥伴能夠節省更多寶貴的時間去做更多的事。

不廢話,回到正題, 首先貼上一個衆所周知的庫 SystemBarTint
我只要這個類
https://github.com/jgilfelt/SystemBarTint/blob/master/library/src/com/readystatesoftware/systembartint/SystemBarTintManager.java
然後複製到你的工程
這裏寫圖片描述
這個類我就不多說了, 就是兼容4.x以上沉浸透明狀態欄的 一個兼容類, 有空可以研究下
#開始
先貼工具類, 有部分代碼參考自網上並有做改動, 但這,不重要…

 
public class StatusBarUtil {
    public final static int TYPE_MIUI = 0;
    public final static int TYPE_FLYME = 1;
    public final static int TYPE_M = 3;//6.0

    @IntDef({TYPE_MIUI,
            TYPE_FLYME,
            TYPE_M})
    @Retention(RetentionPolicy.SOURCE)
    @interface ViewType {
    }

    /**
     * 修改狀態欄顏色,支持4.4以上版本
     *
     * @param colorId 顏色
     */
    public static void setStatusBarColor(Activity activity, int colorId) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.setStatusBarColor(colorId);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //使用SystemBarTintManager,需要先將狀態欄設置爲透明
            setTranslucentStatus(activity);
            SystemBarTintManager systemBarTintManager = new SystemBarTintManager(activity);
            systemBarTintManager.setStatusBarTintEnabled(true);//顯示狀態欄
            systemBarTintManager.setStatusBarTintColor(colorId);//設置狀態欄顏色
        }
    }

    /**
     * 設置狀態欄透明
     */
    @TargetApi(19)
    public static void setTranslucentStatus(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.x開始需要把顏色設置透明,否則導航欄會呈現系統默認的淺灰色
            Window window = activity.getWindow();
            View decorView = window.getDecorView();
            //兩個 flag 要結合使用,表示讓應用的主體內容佔用系統狀態欄的空間
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            //導航欄顏色也可以正常設置
            //window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            attributes.flags |= flagTranslucentStatus;
            //int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            //attributes.flags |= flagTranslucentNavigation;
            window.setAttributes(attributes);
        }
    }


    /**
     *  代碼實現android:fitsSystemWindows
     *
     * @param activity
     */
    public static void setRootViewFitsSystemWindows(Activity activity, boolean fitSystemWindows) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ViewGroup winContent = (ViewGroup) activity.findViewById(android.R.id.content);
            if (winContent.getChildCount() > 0) {
                ViewGroup rootView = (ViewGroup) winContent.getChildAt(0);
                if (rootView != null) {
                    rootView.setFitsSystemWindows(fitSystemWindows);
                }
            }
        }

    }


    /**
     * 設置狀態欄深色淺色切換 
     */
    public static boolean setStatusBarDarkTheme(Activity activity, boolean dark) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                setStatusBarFontIconDark(activity, TYPE_M, dark);
            } else if (OSUtils.isMiui()) {
                setStatusBarFontIconDark(activity, TYPE_MIUI, dark);
            } else if (OSUtils.isFlyme()) {
                setStatusBarFontIconDark(activity, TYPE_FLYME, dark);
            } else {//其他情況
                return false;
            }

            return true;
        }
        return false;
    }

    /**
     * 設置 狀態欄深色淺色切換
     */
    public static boolean setStatusBarFontIconDark(Activity activity, @ViewType int type,boolean dark) {
        switch (type) {
            case TYPE_MIUI:
                return setMiuiUI(activity, dark);
            case TYPE_FLYME:
                return setFlymeUI(activity, dark);
            case TYPE_M:
            default:
                return setCommonUI(activity,dark);
        }
    }

    //設置6.0 狀態欄深色淺色切換
    public static boolean setCommonUI(Activity activity, boolean dark) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = activity.getWindow().getDecorView();
            if (decorView != null) {
                int vis = decorView.getSystemUiVisibility();
                if (dark) {
                    vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                } else {
                    vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                }
                if (decorView.getSystemUiVisibility() != vis) {
                    decorView.setSystemUiVisibility(vis);
                }
                return true;
            }
        }
        return false;

    }

    //設置Flyme 狀態欄深色淺色切換
    public static boolean setFlymeUI(Activity activity, boolean dark) {
        try {
            Window window = activity.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //設置MIUI 狀態欄深色淺色切換
    public static boolean setMiuiUI(Activity activity, boolean dark) {
        try {
            Window window = activity.getWindow();
            Class<?> clazz = activity.getWindow().getClass();
            @SuppressLint("PrivateApi") Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            int darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getDeclaredMethod("setExtraFlags", int.class, int.class);
            extraFlagField.setAccessible(true);
            if (dark) {    //狀態欄亮色且黑色字體
                extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
            } else {
                extraFlagField.invoke(window, 0, darkModeFlag);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //獲取狀態欄高度
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier(
                "status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}

好了,這個類 支持了 設置狀態欄透明, 設置狀態欄顏色, 支持了狀態欄深色淺色切換(則狀態欄上的文字圖標顏色)

停!

如果你在看這篇文章, 先不要看別的文章 (23333…) .因爲可能會擾亂你的思路,導致你無法理解和使用, 並且你亂入的代碼會干擾這邊的代碼正常工作, 先刪掉你在別的文章的代碼修改, 相信我, 我這邊啥都不用做, 你絕對能以最簡單的方式 讓你的項目實現沉浸狀態欄兼容~ 包括圖片沉浸!

前期準備:
我就怕你搞了一堆在別的文章的配置,所以我還是要說下以下代碼不能出現:
全局搜索你的代碼裏 是否有 android:fitsSystemWindows , 刪掉!, 沒錯 刪掉!!!
檢查你的values、values-v19、values-v21等 是否配置了
如下item標籤

// values-v19。v19 開始有 android:windowTranslucentStatus 這個屬性
<style name="TranslucentTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
</style>

// values-v21。5.0 以上提供了 setStatusBarColor()  方法設置狀態欄顏色。
<style name="TranslucentTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowTranslucentStatus">false</item>
    <item name="android:windowTranslucentNavigation">true</item>
    <!--Android 5.x開始需要把顏色設置透明,否則導航欄會呈現系統默認的淺灰色-->
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

凡是在style.xml中 有關 windowTranslucentNavigation、windowTranslucentStatus、statusBarColor 統統刪掉,全部刪掉~
因爲 我們要通過代碼去實現, xml中的各種屬性全部不要寫, 避免代碼出現互相干擾, 會出現各種 爲啥啊無效啊的bug

這裏我要吐槽一下, 我瀏覽過很多文章博客, 關於狀態欄適配, 一會兒在java 設置setFitsSystemWindows setStatusBarColor 一會兒又回到佈局裏設置 android:fitsSystemWindows=“xxx” ,一會兒在style 配置 android:windowTranslucentStatus等 一會兒又使用工具類 設置FLAG_TRANSLUCENT_NAVIGATION …,然後還什麼4.4 5.x各一份 style ,甚至還拿colorPrimary來亂入一通, 搞得是真的亂! 不信你看完我寫的之後再去看別的, 有的說的不全 比如漏了圖片如何沉浸沒講 , 或者是漏了圖片沉浸後 佈局也跟着沉浸進狀態欄如何解決沒講… 唉…

好了干擾已全部去除,開始適配

首先在Activity 的setContentView 下一行編寫如下代碼(一般你可以寫到你的BaseActivity裏,否則你每個activity都得寫一次)

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.xxx);
   
   //這裏注意下 因爲在評論區發現有網友調用setRootViewFitsSystemWindows 裏面 winContent.getChildCount()=0 導致代碼無法繼續
   //是因爲你需要在setContentView之後纔可以調用 setRootViewFitsSystemWindows 
   
   //當FitsSystemWindows設置 true 時,會在屏幕最上方預留出狀態欄高度的 padding
   StatusBarUtil.setRootViewFitsSystemWindows(this,true);
   //設置狀態欄透明
   StatusBarUtil.setTranslucentStatus(this);
   //一般的手機的狀態欄文字和圖標都是白色的, 可如果你的應用也是純白色的, 或導致狀態欄文字看不清
   //所以如果你是這種情況,請使用以下代碼, 設置狀態使用深色文字圖標風格, 否則你可以選擇性註釋掉這個if內容
   if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
        //如果不支持設置深色風格 爲了兼容總不能讓狀態欄白白的看不清, 於是設置一個狀態欄顏色爲半透明,
        //這樣半透明+白=灰, 狀態欄的文字能看得清
        StatusBarUtil.setStatusBarColor(this,0x55000000);
   } 
}

上面先這樣 由於界面風格很多, 比如同一個app有 的界面是黑色風格的頁面, 有的是白色風格的頁面,有的是頂部是圖片的界面希望沉浸進去 這樣更好看, 同時 此時狀態欄文字要跟隨改變

其實都不用我解釋了 就按自己需求 配置唄,工具類都寫好功能了.
比如我這個 4個不同的fragment,有一個是白色, 另外兩個是頂部是圖片的
我是這樣切換狀態欄文字深淺色的,你們參考下
0界面設置狀態欄黑色圖標
這裏寫圖片描述
123界面設置狀態欄白色圖標
這裏寫圖片描述
代碼:
這裏寫圖片描述
你還可以隨時使用
StatusBarUtil.setStatusBarColor(this,顏色值);
設置不同fragment時 的狀態欄顏色

至此 你明白了設置狀態欄顏色 和 隨界面切換時 該怎麼改狀態欄顏色或狀態欄文字顏色, 沒錯,你沒有漏看! 用了我這個你不需要在xml中 或style中設置各種屬性, 也不用判斷什麼4.4 啊 5.0 啊 6.0啊怎麼處理… 就是這麼神奇!~

現在來一個蛋疼的問題

我要把圖片也沉浸進去!!!

通常 你使用我剛纔的代碼時 相同顏色的界面沒啥問題,比如:
這裏寫圖片描述
但 當你界面頂部是圖片界面的時候 或者 標題顏色不一樣時
成了這鬼樣子,
這裏寫圖片描述
這是因爲我前面設置了 setRootViewFitsSystemWindows(this,true); 於是帶有 paddingTop=狀態欄高度 的效果

首先 你可以選擇兩種應對辦法
如果頂部不是圖片佈局 , 可以直接使用 setStatusBarColor 設置相同顏色即可
如果頂部是圖片佈局, 那麼問題來了
這裏注意了

想要圖片沉浸, 必須設置fitsSystemWindows=false, 以去掉padding效果, 然後想辦法 把圖片上層的 其他View 整體 paddingTop=狀態欄高 讓其他View向下挪動

這句話一定要理解
,現在試試在當前帶圖片的activity 重新設置setRootViewFitsSystemWindows(this,false);
效果如下(你會發現圖標跑左邊了, 請無視, 將就看,我是在現有項目中演示的 )
去掉padding效果後 圖片沉浸了! 但內容進入了狀態欄裏 被遮擋.
這裏寫圖片描述
那, 怎麼以最方便的方式 讓整個內容佈局 往下挪動?

有很多教程都是寫的是在代碼裏 findView 然後設置padding , 很是麻煩, 要是多個界面都這樣 代碼豈止亂?
曾經試圖在xml中使用 狀態欄高度值 ,結果發現這是幾乎是不可能的, 因爲編譯後 xml固定了值,除非使用反射, 但這到了安卓9.0不能反射系統api怎麼辦…
於是我想出了一種解決辦法

自定義一個View ,用來做狀態欄高度佔位

/**
 * 作者:東芝
 * 功能:狀態欄高度View,用於沉浸佔位
 */

public class StatusBarHeightView extends LinearLayout {
    private int statusBarHeight;
    private int type;

    public StatusBarHeightView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public StatusBarHeightView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public StatusBarHeightView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr);
        init(attrs);


    }

    private void init(@Nullable AttributeSet attrs) {

        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if(resourceId>0) {
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            }
        }else{
            //低版本 直接設置0
            statusBarHeight = 0;
        }
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.StatusBarHeightView);
            type = typedArray.getInt(R.styleable.StatusBarHeightView_use_type, 0);
            typedArray.recycle();
        }
        if (type == 1) {
            setPadding(getPaddingLeft(), statusBarHeight, getPaddingRight(), getPaddingBottom());
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (type == 0) {
            setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                    statusBarHeight);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
 
}

attrs.xml

    <declare-styleable name="StatusBarHeightView">
        <attr name="use_type" format="integer">
            <enum name="use_height" value="0" />
            <enum name="use_padding_top" value="1" />
        </attr>
    </declare-styleable>

代碼很簡單, 就是寫一個View, 支持paddingTop= 狀態欄高度值 的View,
解釋下兩個類型:
use_height: 設置當前佈局高度=狀態欄高度值 用於無子View時的佔位
use_padding_top: 設置當前頂部padding=狀態欄高度值 用於有子View時的佔位
適配低於4.4時 佔位View的高度爲0 所以不可見

使用方法, 用StatusBarHeightView 來包住你要往下移動的內容! 單獨留出要沉浸的View不包住,
舉例:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >		
     <!--頂部的需要沉浸的圖片View 或其他東西 視頻View  等 -->     
     <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@mipmap/icon_top_bg"
        android:scaleType="centerCrop" />
                    
<!-- app:use_type="use_padding_top 向上paddingTop狀態欄高度-->
	<com.xxx.views.StatusBarHeightView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="@dimen/widget_size_5"
        app:use_type="use_padding_top"
        android:orientation="vertical" >
		 <!--這裏放內容佈局或View-->
         <ImageView
              android:id="@+id/ivUserShare"
              android:layout_width="@dimen/title_height"
              android:layout_height="@dimen/title_height"
              android:padding="@dimen/widget_size_10"
              android:src="@mipmap/icon_share_white" />
                        
	</com.xxx.views.StatusBarHeightView>
</RelativeLayout>
//不要忘記了, 在當前activity onCreate中設置 取消padding,  因爲這個padding 我們用代碼實現了,不需要系統幫我
StatusBarUtil.setRootViewFitsSystemWindows(this,false);

java 代碼這邊不需要改動, 運行app即可.
完美!
這裏寫圖片描述

結束

值得注意的是 如果你按我那樣去做, 狀態欄顏色無法被修改, 請檢查上層佈局是否設置了背景
或者受了全局主題的

<item name="android:windowBackground">@color/xxx</item>

的顏色影響

好了,可能有不對的地方望指出, 或出現任何兼容性適配問題 歡迎在下方評論

關於兼容性

該功能已通過大量真機測試, 低版本4.1到安卓9.0 的手機均未出現狀態欄錯位,顏色重疊顯示不清,等問題,而且 app發佈到國內外均未反映關於 這個狀態欄適配方案導致的bug 或 其他問題, 可放心食用. 至於有一些文章說到 側滑佈局 DrawerLayout 需要特殊處理… 放心, 本文的兼容方案是獲取activity 根層佈局來處理實現兼容的, 與activity裏面是什麼佈局 無關.

================================================================

================================================================

補充:

================================================================

================================================================

感謝@Narbolo 的提醒, 漏了個Rom類型判斷的工具類,現在貼上


public class OSUtils {

    public static final String ROM_MIUI = "MIUI";
    public static final String ROM_EMUI = "EMUI";
    public static final String ROM_FLYME = "FLYME";
    public static final String ROM_OPPO = "OPPO";
    public static final String ROM_SMARTISAN = "SMARTISAN";
    public static final String ROM_VIVO = "VIVO";
    public static final String ROM_QIKU = "QIKU";

    private static final String KEY_VERSION_MIUI = "ro.miui.ui.version.name";
    private static final String KEY_VERSION_EMUI = "ro.build.version.emui";
    private static final String KEY_VERSION_OPPO = "ro.build.version.opporom";
    private static final String KEY_VERSION_SMARTISAN = "ro.smartisan.version";
    private static final String KEY_VERSION_VIVO = "ro.vivo.os.version";

    private static String sName;
    private static String sVersion;

    public static boolean isEmui() {
        return check(ROM_EMUI);
    }

    public static boolean isMiui() {
        return check(ROM_MIUI);
    }

    public static boolean isVivo() {
        return check(ROM_VIVO);
    }

    public static boolean isOppo() {
        return check(ROM_OPPO);
    }

    public static boolean isFlyme() {
        return check(ROM_FLYME);
    }

    public static boolean is360() {
        return check(ROM_QIKU) || check("360");
    }

    public static boolean isSmartisan() {
        return check(ROM_SMARTISAN);
    }

    public static String getName() {
        if (sName == null) {
            check("");
        }
        return sName;
    }

    public static String getVersion() {
        if (sVersion == null) {
            check("");
        }
        return sVersion;
    }

    public static boolean check(String rom) {
        if (sName != null) {
            return sName.equals(rom);
        }

        if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_MIUI))) {
            sName = ROM_MIUI;
        } else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_EMUI))) {
            sName = ROM_EMUI;
        } else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_OPPO))) {
            sName = ROM_OPPO;
        } else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_VIVO))) {
            sName = ROM_VIVO;
        } else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_SMARTISAN))) {
            sName = ROM_SMARTISAN;
        } else {
            sVersion = Build.DISPLAY;
            if (sVersion.toUpperCase().contains(ROM_FLYME)) {
                sName = ROM_FLYME;
            } else {
                sVersion = Build.UNKNOWN;
                sName = Build.MANUFACTURER.toUpperCase();
            }
        }
        return sName.equals(rom);
    }

    public static String getProp(String name) {
        String line = null;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + name);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章