Material Design 之 側(cè)邊欄與 Status Bar 不得不說的故事

再過2個(gè)小時(shí)就是2015蘋果春季發(fā)布會了,在兩個(gè)小時(shí)的閑暇時(shí)間里,順便鼓搗一下 Material Design 的側(cè)邊欄,沒想到又是心酸血淚史。

Material Design 中,側(cè)邊欄是一個(gè)可以從屏幕左側(cè)滑出的抽屜式的組件。如下效果圖所示,當(dāng)側(cè)邊欄滑出時(shí),它處于 Status Bar 之下,并且覆蓋了 Status Bar 原有的顏色(圖中 Dark Primary Color 所指組件)。按照 Material Design 中 Status Bar 的設(shè)計(jì),Status Bar 的顏色會深于 ActionBar (圖中 Primary Color 所指組件),效果圖由于壓縮的原因,可能不太明顯。

效果圖

所以,要實(shí)現(xiàn)如下效果,有如下3件事需要完成:

  • 為了能使 ActionBar 獲得最大的擴(kuò)展,我們使用 ToolBar 代替 ActionBar,并將其顏色設(shè)置為 Material Design 中的 Primary Color
  • 將 Status Bar 的顏色設(shè)置為 Material Design 中的 Dark Primary Color
  • 將側(cè)邊欄插入于 Status Bar 和 頁面內(nèi)容之間

前兩步中,正常的實(shí)現(xiàn)方式如下:

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="windowActionBar">false</item>
        <item name="android:colorPrimary">@color/theme_primary</item>
        <item name="android:colorPrimaryDark">@color/theme_dark_primary</item>
</style>

運(yùn)行程序,效果正是我們想要的(請不要在意配色怎么這么丑的細(xì)節(jié), = =)。

效果圖

下面,按照我們正常的方式添加側(cè)邊欄組件,為了能使側(cè)邊欄正常的顯示在 Status Bar 之下,在 values-v21/styles.xml中添加入

<item name="android:windowTranslucentStatus">true</item>

并將 Activity 繼承自 ActionBarActivity, 并使用如下布局:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id="@+id/content_relative"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
        <include
            android:id="@+id/toolbar"
            layout="@layout/framelayout_toolbar_with_search"/>
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/toolbar"
            android:background="@android:color/white">
        </FrameLayout>
    </RelativeLayout>
    <!-- navigation 中根目錄已經(jīng)添加  android:fitsSystemWindows="false" 屬性 -->
    <include layout="@layout/navigation"/>
</android.support.v4.widget.DrawerLayout>

duang! 問題出現(xiàn)了,側(cè)邊欄正常顯示,但是之前設(shè)置的 Status Bar 的顏色失效了。

Status Bar 的顏色失效

但是,將剛才添加的狀態(tài)欄透明的屬性刪除

<item name="android:windowTranslucentStatus">true</item>

duang!duang! 問題又出現(xiàn)了,側(cè)邊欄根本沒有在 SystemBar 之下。

側(cè)邊欄沒有在 Status Bar 之下

擦擦擦,這兩個(gè)屬性沖突了

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>

為了解決這個(gè)問題,我拆解了谷歌官方應(yīng)用,終于發(fā)現(xiàn)了這個(gè)秘密(可能是我才疏學(xué)淺,后來才發(fā)現(xiàn)官方的 Android Demo 里就有, 哈哈)

所以現(xiàn)在是解決問題的時(shí)間了。

首先,需要在應(yīng)用中添加 ScrimInsetsFrameLayout 開源組件。

** ScrimInsetsFrameLayout.java **

/*
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.apps.iosched.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.google.samples.apps.iosched.R;

/**
 * A layout that draws something in the insets passed to {@link #fitSystemWindows(Rect)}, i.e. the area above UI chrome
 * (status and navigation bars, overlay action bars).
 */
public class ScrimInsetsFrameLayout extends FrameLayout {
    private Drawable mInsetForeground;

    private Rect mInsets;
    private Rect mTempRect = new Rect();
    private OnInsetsCallback mOnInsetsCallback;

    public ScrimInsetsFrameLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ScrimInsetsView, defStyle, 0);
        if (a == null) {
            return;
        }
        mInsetForeground = a.getDrawable(R.styleable.ScrimInsetsView_insetForeground);
        a.recycle();

        setWillNotDraw(true);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        mInsets = new Rect(insets);
        setWillNotDraw(mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(this);
        if (mOnInsetsCallback != null) {
            mOnInsetsCallback.onInsetsChanged(insets);
        }
        return true; // consume insets
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            // Top
            mTempRect.set(0, 0, width, mInsets.top);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Bottom
            mTempRect.set(0, height - mInsets.bottom, width, height);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Left
            mTempRect.set(0, mInsets.top, mInsets.left, height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Right
            mTempRect.set(width - mInsets.right, mInsets.top, width, height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(null);
        }
    }

    /**
     * Allows the calling container to specify a callback for custom processing when insets change (i.e. when
     * {@link #fitSystemWindows(Rect)} is called. This is useful for setting padding on UI elements based on
     * UI chrome insets (e.g. a Google Map or a ListView). When using with ListView or GridView, remember to set
     * clipToPadding to false.
     */
    public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
        mOnInsetsCallback = onInsetsCallback;
    }

    public static interface OnInsetsCallback {
        public void onInsetsChanged(Rect insets);
    }
}

然后創(chuàng)建該組件的自定義屬性,使組件的 insetForeground 屬性生效

values/attrs.xml

<declare-styleable name="ScrimInsetsView"> 
    <attr name="insetForeground" format="reference|color" />
</declare-styleable>

更新你的 Activity 的布局文件,需要注意的是,確保 DrawerLayout 和 ScrimInsetsFrameLayout 都添加了 android:fitsSystemWindows 屬性,并設(shè)置為 true

layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <RelativeLayout
        android:id="@+id/content_relative"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include
            android:id="@+id/toolbar"
            layout="@layout/framelayout_toolbar_with_search"/>
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/toolbar"
            android:background="@android:color/white">
        </FrameLayout>
    </RelativeLayout>
    <com.google.samples.apps.iosched.ui.widget.ScrimInsetsFrameLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scrimInsetsFrameLayout"
        android:layout_width="@dimen/navigation_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:elevation="10dp"
        android:fitsSystemWindows="true"
        app:insetForeground="#4000">
        <include layout="@layout/navigation"/>
    </com.google.samples.apps.iosched.ui.widget.ScrimInsetsFrameLayout>
</android.support.v4.widget.DrawerLayout>

最后,更新主題文件,使側(cè)邊欄顯示與 Status Bar 之下

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="windowActionBar">false</item>
        <item name="android:colorPrimary">@color/theme_primary</item>
        <item name="android:colorPrimaryDark">@color/theme_dark_primary</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
</style>

最最后,就是見證奇跡的時(shí)刻(邊看直播邊碼文字,剛好在發(fā)布會結(jié)束時(shí)完成,Macbook 很贊,Apple Watch 除外觀之外,還不錯(cuò)的說)

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

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容