[英] 怎样在 5 分钟内使 Drawer 在状态栏下可见?

1,251 阅读1分钟
原文链接: matthewwear.xyz
本文已经翻译成中文《[译] 怎样在 5 分钟内使 Drawer 在状态栏下可见?》,欢迎参加「掘金翻译计划」,翻译优质的技术文章。

You probably know that Google's Material Design spec specifies to make your Navigation Drawer span the full height of the screen, including behind the status bar ... Everything behind the drawer is still visible but darkened by a scrim.

Yet, many apps look like this when their navigation drawer is opened

Here is how to bring this element up to spec

Extend your theme

You probably already have a theme defined for your Activity that contains the navigation drawer

  
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
  

To get started, first, just create a new Theme that extends AppTheme

vaules/styles.xml

  
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>

v21/styles.xml

  
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
  

And make sure to specify that your Activity now uses this theme, like so

Setup your DrawerLayout

Second, go to where your DrawerLayout is defined in your layout, set your insetForegroundColor (you don't have to, but if you want to control the color of the ScrimInsetLayout) and confirm that fitsSystemWindow is set.


That is it.

Of course, if you later want to change the color of the status bar or the scrim inset layout programmatically, there are setters for both in DrawerLayout.

drawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.wierd_green));  
drawerLayout.setScrimColor(ContextCompat.getColor(this, R.color.wierd_transparent_orange));  

Thanks for reading. If you know of a better way to accomplish what I've shared, then please correct me in the comments, it would be much appreciated.

* The Below Added June 5, 2016*

If you subclass DrawerLayout

The above might not work for you as is if you subclass DrawerLayout. AppCompat is placing a android.support.design.internal.ScrimInsetsFrameLayout inside the DrawerLayout for you, and it doesn't seem to do this if you subclass DrawerLayout.

So, if you're subclassing DrawerLayout and not placing a ScrimInsetsFrameLayout, you need to, like so:

activity_with_drawer_layout.xml



    

    

  

Place a ScrimInsetsFrameLayout in your layout file of the drawer's view, like so:

navigation_fragment_layout.xml