Android 視圖 狀態(tài)欄

【Android 視圖 狀態(tài)欄】

[Digging] Android Translucent Status Bar
Android狀態(tài)欄微技巧,帶你真正理解沉浸式模式
Android 狀態(tài)欄著色實踐

演示代碼傳送門

全屏,不保留狀態(tài)欄文字(Splash頁面,歡迎頁面)

這個效果大家腦補下,就不貼圖了
首先在style.xml中設置為noActionBar的主題,這是必須的

<style name="fullScreen" parent="Theme.AppCompat.DayNight.NoActionBar">
</style>

方式有三種

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fullscreen_no_text);
    //方式一
    //getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //方式二
    //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
    //方式三 style.xml中配置
    //<style name="fullScreen" parent="Theme.AppCompat.DayNight.NoActionBar">
    //        <item name="android:windowFullscreen">true</item>
    //</style>
}

全屏保留狀態(tài)欄文字(頁面上部有Banner圖)

現(xiàn)在項目,大部分向下支持到19,所以先不考慮太低版本的情況

Window window = getWindow();
//默認API 最低19 
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    ViewGroup contentView = window.getDecorView().findViewById(Window.ID_ANDROID_CONTENT);
    contentView.getChildAt(0).setFitsSystemWindows(false);
}

標題欄與狀態(tài)欄顏色一致 xml中配置

<style name="status_toolbar_same_color" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/status_toolBar_same_color</item>
    <item name="colorPrimaryDark">@color/status_toolBar_same_color</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

我們能看到這種處理方式,是可以解決一些業(yè)務場景,但是如果在低于21版本手機上就不管用了,那怎么辦呢?請接著往下看

Window window = getWindow();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.status_toolBar_same_color));
    } else {
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ViewGroup systemContent = findViewById(android.R.id.content);

        View statusBarView = new View(this);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight());
        statusBarView.setBackgroundColor(getResources().getColor(R.color.status_toolBar_same_color));

        systemContent.getChildAt(0).setFitsSystemWindows(true);

        systemContent.addView(statusBarView, 0, lp);

    }

適配后的結果:

不同F(xiàn)ragment中對StatusBar的處理不一樣

<android.support.v7.widget.Toolbar
    android:id="@+id/base_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@android:color/holo_blue_dark">

    <TextView
        android:id="@+id/base_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@android:color/black" />
</android.support.v7.widget.Toolbar>

<FrameLayout
    android:id="@+id/base_container"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

</FrameLayout>

上述代碼是兩個Fragment所依附的Activity對應的部分layout

private void addStatusBar() {
    //條件狀態(tài)欄透明,要不然不會起作用
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    if (mStatusBarView == null) {
        mStatusBarView = new View(FragmentStatusAndActionBarActivity.this);
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int statusBarHeight = getStatusBarHeight();
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(screenWidth, statusBarHeight);
        mStatusBarView.setLayoutParams(params);
        mStatusBarView.requestLayout();

        //獲取根布局
        ViewGroup systemContent = findViewById(android.R.id.content);
        ViewGroup userContent = (ViewGroup) systemContent.getChildAt(0);
        userContent.setFitsSystemWindows(false);
        userContent.addView(mStatusBarView, 0);
    }
}

上面是對應Activity中的布局,意思就是不使用系統(tǒng)提供的ActionBar,使用ToolBar來代替(網上一大推代替的方法),下面的代碼中設置,狀態(tài)欄透明,并且設置了sitFitSystemWindow(false),通過這些操作,我們相當于把系統(tǒng)的StatusBar,ActionBar,都干掉了,那么接下來,我們就可以模擬創(chuàng)建出StatusBaruserContent.addView(mStatusBarView, 0);那么現(xiàn)在我們就可以自己控制statusBar和ActionBar,顯示什么顏色?消失還是隱藏?

ToolBar顯示的Fragment:

 @Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    mActivity.mToolbar.setVisibility(View.VISIBLE);//設置ToolBar顯示
    //設置statusBar的顏色
    mActivity.mStatusBarView.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright));
}

ToolBar隱藏的Fragment

@Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    mActivity.mToolbar.setVisibility(View.GONE);//設置ToolBar消失
    //設置statusBar的顏色
    mActivity.mStatusBarView.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_light));
}
復制代碼

設置狀態(tài)欄文字的顏色

 //設置白底黑字
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}

但是需要注意的是:目前只有android原生6.0以上支持修改狀態(tài)欄字體
除此國內廠商小米、魅族也開放了修改狀態(tài)欄字體的方式

小米 MIUI6
魅族 Flyme

切換fragment時,toolBar和statusbar顯示與否、statusBar顏色、status文字顏色

評論區(qū),有同學提出能否"不同F(xiàn)ragment中切換狀態(tài)欄顏色和狀態(tài)欄文字的顏色,甚至同時切換風格(純色狀態(tài)欄變成banner往上頂?shù)臓顟B(tài)欄)的情況",這種情況肯定是沒有問題的,也不難,現(xiàn)在狀態(tài)欄和標題欄都是我們自己,我們想讓它怎么樣,它不得乖乖聽話,對不~

先上圖:

gif

其實調整的不多,這里我只貼下關鍵代碼,gitub代碼倉庫已更新,大家可以clone看完成代碼

這是只有Banner的fragment:

 @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //設置ToolBar隱藏
        mActivity.mToolbar.setVisibility(View.GONE);
        //設置statusBar的隱藏
        mActivity.mStatusBarView.setVisibility(View.GONE);
        //恢復默認statusBar文字顏色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            mActivity.getWindow().getDecorView().setSystemUiVisibility(View.VISIBLE);
        mActivity.mStatusBarView.setVisibility(View.GONE);
    }

改變statusBar字體顏色

@Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    //設置ToolBar顯示
    mActivity.mToolbar.setVisibility(View.VISIBLE);
    //設置ToolBar的顏色
    mActivity.mToolbar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
    //設置statusBar的顏色
    mActivity.mStatusBarView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
    //設置statusBar顯示
    mActivity.mStatusBarView.setVisibility(View.VISIBLE);
    //設置statusBar字體顏色
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        mActivity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}

擴展

Activity中window是怎么回事?里面有什么View/ViewGroup

寫了個方法,將整個Window內的View都打印出來了

private void printChildView(ViewGroup viewGroup) {
    Log.i("printView-ViewGroup", viewGroup.getClass().getSimpleName() + "的子View和數(shù)量:" + viewGroup.getChildCount());
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
        String simpleName = viewGroup.getChildAt(i).getClass().getSimpleName();
        Log.i("printView-ChildView", simpleName);
    }
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
        if (viewGroup.getChildAt(i) instanceof ViewGroup) {
            printChildView((ViewGroup) viewGroup.getChildAt(i));
        }
    }
}

這是結果

printView-ViewGroup: DecorView的子View和數(shù)量:1
printView-ChildView: LinearLayout
printView-ViewGroup: LinearLayout的子View和數(shù)量:2
printView-ChildView: ViewStub
printView-ChildView: FrameLayout
printView-ViewGroup: FrameLayout的子View和數(shù)量:1
printView-ChildView: ActionBarOverlayLayout
printView-ViewGroup: ActionBarOverlayLayout的子View和數(shù)量:2
printView-ChildView: ContentFrameLayout
printView-ChildView: ActionBarContainer
printView-ViewGroup: ContentFrameLayout的子View和數(shù)量:2
printView-ChildView: View
printView-ChildView: ConstraintLayout
printView-ViewGroup: ConstraintLayout的子View和數(shù)量:1
printView-ChildView: AppCompatTextView
printView-ViewGroup: ActionBarContainer的子View和數(shù)量:2
printView-ChildView: Toolbar
printView-ChildView: ActionBarContextView
printView-ViewGroup: Toolbar的子View和數(shù)量:1
printView-ChildView: AppCompatTextView
printView-ViewGroup: ActionBarContextView的子View和數(shù)量:0
復制代碼

我們根據結果畫一個分布圖


上述這個ContentFrameLayout就是我們Activity中通過setContentView(View)添加的,至于其中的View是我們自己設備的statusbar,把這個圖畫出來,希望能起一個拋磚引玉的作用,有想法的可以繼續(xù)往下研究,我這里就不研究了,有想法的可以評論。

setFitsSystemWindows()是什么

fitsSystemWindows代表的是:當設置SystemBar(包含StatusBar&NavigationBar)透明之后,通過添加flag的方式 將fitsSystemWindows至為true,則還是為SystemBar預留空間,當設置為false的時候,就是不為SystemBar預留空間,比如我們設置狀態(tài)欄和標題欄的時候,如果不設置fitSystemWindows為true的話,就變成了

這肯定不是我們想要的效果,但是為什么會這樣呢?
我們思考一中,發(fā)現(xiàn)ToolBar和我們的開發(fā)者通過setContentView是在一個ActionBarOverlayLayout中,那我就去看看這個View


在系統(tǒng)的 frameworks\support\v7\appcompat\res\layout\abc_screen_toolbar.xml下我們看到了ActionBarOverlayLayout的布局

<android.support.v7.internal.widget.ActionBarOverlayLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/decor_content_parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

    <include layout="@layout/abc_screen_content_include"/>

    <android.support.v7.internal.widget.ActionBarContainer
            android:id="@+id/action_bar_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            style="?attr/actionBarStyle"
            android:touchscreenBlocksFocus="true"
            android:gravity="top">

        <android.support.v7.widget.Toolbar
                android:id="@+id/action_bar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:navigationContentDescription="@string/abc_action_bar_up_description"
                style="?attr/toolbarStyle"/>

        <android.support.v7.internal.widget.ActionBarContextView
                android:id="@+id/action_context_bar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:theme="?attr/actionBarTheme"
                style="?attr/actionModeStyle"/>

    </android.support.v7.internal.widget.ActionBarContainer>

</android.support.v7.internal.widget.ActionBarOverlayLayout>
復制代碼

通過includy引入的ContentView abc_screen_content_include.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v7.internal.widget.ContentFrameLayout
            android:id="@id/action_bar_activity_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:foregroundGravity="fill_horizontal|top"
            android:foreground="?android:attr/windowContentOverlay" />

</merge>
復制代碼

layout布局很普通,沒有什么特別之處,我看到這時候,猜想:當我們設置了fitSystemwindow(false),是不是在這個ActionBarOverlayLayoutonLyout()過程會對相應的布局做調整。然后窮就去他的onLayout()里看:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    final int count = getChildCount();

    final int parentLeft = getPaddingLeft();
    final int parentRight = right - left - getPaddingRight();

    final int parentTop = getPaddingTop();
    final int parentBottom = bottom - top - getPaddingBottom();

    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (child.getVisibility() != GONE) {
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();

            final int width = child.getMeasuredWidth();
            final int height = child.getMeasuredHeight();

            int childLeft = parentLeft + lp.leftMargin;
            int childTop = parentTop + lp.topMargin;

            child.layout(childLeft, childTop, childLeft + width, childTop + height);
        }
    }
}
復制代碼

然而毛都沒有。。。懵逼了,layout的參數(shù)都是來自布局文件里的,后來我跟著setFitSystemWindow()看到一個方法,就是這個fitSystemWindows(Rect insets)它的注釋說明里有The content insets tell you the space that the status bar,應該是調用這個方法進行設置的,但是怎么調用的,目前我還沒有找到,希望懂得同學指點迷津,萬分感謝!

 /**
     * Called by the view hierarchy when the content insets for a window have
     * changed, to allow it to adjust its content to fit within those windows.
     * The content insets tell you the space that the status bar, input method,
     * and other system windows infringe on the application's window.
     ...
    protected boolean fitSystemWindows(Rect insets) {
        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
            if (insets == null) {
                // Null insets by definition have already been consumed.
                // This call cannot apply insets since there are none to apply,
                // so return false.
                return false;
            }
            // If we're not in the process of dispatching the newer apply insets call,
            // that means we're not in the compatibility path. Dispatch into the newer
            // apply insets path and take things from there.
            try {
                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
            } finally {
                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
            }
        } else {
            // We're being called from the newer apply insets path.
            // Perform the standard fallback behavior.
            return fitSystemWindowsInt(insets);
        }
    }
復制代碼

引用:

Android 狀態(tài)欄關于開發(fā)的幾件事

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,716評論 25 709
  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 7,294評論 0 17
  • 第二次采訪。 去了一位先鋒藝術家家中作客。對方穿著睡褲接受采訪。上一次見面,因為談論嚴肅的事,一直不拘言笑,又因為...
    Chain在這里閱讀 453評論 0 1
  • 感恩清晨明媚的陽光照滿我的臥室,早晨醒來的第一眼是看到燦爛的陽光,心情很好! 感恩我們小區(qū)的門衛(wèi)每次進出...
    做優(yōu)雅的女人閱讀 132評論 0 0
  • 早起剛好趕上堵車,原本半小時的車程,40分過去了卻還沒有開完半程。在車上的人很多還是中老年人,但是站著的年青人都難...
    秀姨閱讀 390評論 0 0

友情鏈接更多精彩內容