导航抽屉半透明在状态栏上不起作用

91
我正在开发Android项目,正在实现导航抽屉。我正在阅读新的Material Design SpecMaterial Design Checklist
规范指出,滑出面板应该浮在其他所有东西之上,包括状态栏,并且半透明地覆盖状态栏。
我的导航面板位于状态栏上方,但没有任何透明度。我按照谷歌开发者博客中建议的这个SO帖子的代码进行了操作,链接在上面How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?下面是我的XML布局
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.Toolbar
            android:id="@+id/my_awesome_toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            android:background="@color/appPrimaryColour" />
    </LinearLayout>
    <LinearLayout android:id="@+id/linearLayout"
        android:layout_width="304dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:fitsSystemWindows="true"
        android:background="#ffffff">
        <ListView android:id="@+id/left_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:choiceMode="singleChoice"></ListView>
    </LinearLayout>
</android.support.v4.widget.DrawerLayout>

以下是我的应用程序主题。
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/appPrimaryColour</item>
        <item name="colorPrimaryDark">@color/appPrimaryColourDark</item>
        <item name="colorAccent">@color/appPrimaryColour</item>
        <item name="windowActionBar">false</item>
        <item name="windowActionModeOverlay">true</item>

    </style>

以下是我的应用程序v21主题。
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/appPrimaryColour</item>
    <item name="colorPrimaryDark">@color/appPrimaryColourDark</item>
    <item name="colorAccent">@color/appPrimaryColour</item>
    <item name="windowActionBar">false</item>
    <item name="windowActionModeOverlay">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

以下是我的onCreate方法

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);

    mDrawerLayout = (DrawerLayout)findViewById(R.id.my_drawer_layout);
    mDrawerList = (ListView)findViewById(R.id.left_drawer);

    mDrawerLayout.setStatusBarBackgroundColor(
        getResources().getColor(R.color.appPrimaryColourDark));

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    {
        LinearLayout linearLayout = 
            (LinearLayout)findViewById(R.id.linearLayout);
        linearLayout.setElevation(30);
    }

下面是我的导航抽屉的截图,显示顶部不是半透明的。

Screenshot showing non transparent over the status bar


请发布您的结果截图。 - Alok Nair
@Boardy,你成功让它工作了吗? - Michele La Ferla
无法在状态栏中设置透明效果,请尝试解决。 - Ronak Gadhia
9个回答

105
你的状态栏背景是白色的,抽屉布局LinearLayout的背景也是白色的。为什么?因为你在DrawerLayout和其中的LinearLayout上设置了fitsSystemWindows="true",这会导致LinearLayout扩展到状态栏后面(透明区域),从而使得抽屉部分的背景也变成了白色。
如果你不想让抽屉延伸到状态栏后面(想要整个状态栏有半透明的背景),你可以做两件事情:
1)你可以简单地从LinearLayout中删除任何背景值,并将其内部内容的背景设为颜色。
2)你可以从LinearLayout中删除fitsSystemWindows="true"。我认为这是一种更合理、更干净的方法。你还可以避免在状态栏下方产生阴影,因为此时你的导航抽屉并没有延伸到那里。
如果您想要抽屉菜单延伸到状态栏后面,并且具有半透明的、与状态栏大小相同的覆盖层,您可以使用 ScrimInsetFrameLayout 作为抽屉内容(ListView)的容器,并使用app:insetForeground="#4000"设置状态栏背景。当然,您可以将#4000更改为任何您想要的颜色。不要忘记在此处保留fitsSystemWindows="true"
或者,如果您不想叠加内容,只想显示纯色,您可以将LinearLayout的背景设置为任何您想要的颜色。不要忘记单独设置内容的背景!
编辑:您不再需要处理这些问题。请参见Design Support Library以获得更简便的导航抽屉/视图实现。

感谢您的帮助。很抱歉回复晚了,最近非常忙碌。我已经设置了另一个赏金以奖励您的答案,就像我最初设置的那样,但它在我实施您的建议之前就结束了。不幸的是,我必须等待23个小时,所以我会尽快添加它。 - Boardy
注意!使用选项1或2时,请确保注意超出绘制范围的情况(可以在手机设置的开发者选项中进行检查)。当我仅设置内容背景时,抽屉后面的所有内容也会被绘制。其他方面都很好,肯定节省了我一些时间 :) - Daiwik Daarun
1
请问您能否解释一下我们需要使用设计支持库的解决方案吗?即使是Chris Banes发布的答案,我仍然遇到了一些问题。 - mDroidd

32

你只需要为状态栏使用一些半透明颜色。将以下行添加到你的v21主题中:

<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/desired_color</item>

不要忘记,color(资源)必须始终以#AARRGGBB的格式表示。这意味着颜色还包括alpha值。


你很厉害,但是... 你能告诉我为什么这只在有抽屉的 Activity 中起作用吗?其他没有抽屉的 Activity 显示状态栏为灰色。 - Joaquin Iurchuk

15

为什么不使用类似这样的东西呢?

<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"
        >

    <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    <ListView
            android:id="@+id/left_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:background="#80111111"/>
</android.support.v4.widget.DrawerLayout>

上述代码使用android:background中的alpha资源来显示操作栏内的透明度。

还有其他通过代码实现此功能的方法,正如其他答案所示。我上面的答案在xml布局文件中完成必要的操作,我认为这种方式更容易进行编辑。


4
可以,但你正在改变什么以及如何回答问题还不清楚。 - rds
将分隔符设置为透明,并在背景颜色中使用 alpha 代码。 - Michele La Ferla

10

这里提到的所有答案都太过陈旧和冗长了。最好的简短解决方案是使用最新NavigationView:

@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
    super.onDrawerSlide(drawerView, slideOffset);

    try {
        //int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
            // Do something for lollipop and above versions

        Window window = getWindow();

        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        // finally change the color to any color with transparency

         window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDarktrans));}

    } catch (Exception e) {

        Crashlytics.logException(e);

    }
}

当您打开抽屉时,这将更改状态栏颜色为透明。

现在,当您关闭抽屉时,您需要再次将状态栏颜色更改为深色。因此,您可以以这种方式完成。

@Override
public void onDrawerClosed(View drawerView) {
   super.onDrawerClosed(drawerView);
    try {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            // Do something for lollipop and above versions

            Window window = getWindow();

            // clear FLAG_TRANSLUCENT_STATUS flag:
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            // finally change the color again to dark
            window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        }
    } catch (Exception e) {
        Crashlytics.logException(e);
    }
}

然后在主布局中添加一行代码:

            android:fitsSystemWindows="true"

你的抽屉布局将会看起来像:

            <android.support.v4.widget.DrawerLayout     
            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:id="@+id/drawer_layout"
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

你的导航视图将会如下所示

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/drawer"
        />

我已经测试过它并且完全可用。希望这能帮助到某些人。虽然这可能不是最好的方法,但它运行平稳且易于实现。如果有用,请标记一下。祝编码愉快 :)


谢谢!这节省了我很多时间。它与最新的NavigationView完美地配合使用。对于任何无法使其工作的人,请确保选择具有一定透明度的颜色作为“colorPrimaryDarktrans”,否则您将看不到任何变化。 - Rui
完美运行,唯一的缺点是当 onDrawerClosed 被调用时状态栏会“闪烁”,但如果你将透明颜色 colorPrimaryDarktrans 设置为 #05000000,几乎不会被注意到。 - Kirill Karmazin

8
你需要将你的导航抽屉布局包裹在一个ScrimLayout中。 ScrimLayout基本上会在你的导航抽屉布局上绘制一个半透明的矩形。 要检索插图的大小,只需在ScrimLayout中覆盖fitSystemWindows即可。
@Override
protected boolean fitSystemWindows(Rect insets) {
    mInsets = new Rect(insets);
    return true;
}

稍后重写onDraw方法以绘制半透明矩形。
您可以在Google IO应用程序源代码中找到一个示例实现。这里您可以看到它在布局xml中的使用方式。

5
如果您希望导航面板覆盖状态栏并且在状态栏上半透明,Google I/O Android App源代码提供了一个好的解决方案(Play商店中的APK版本未更新到最新版本)。
首先,您需要一个ScrimInsetFrameLayout
/*
* 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.
*/

/**
* 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);
    }
}

然后,在您的XML布局中更改此部分。
<LinearLayout android:id="@+id/linearLayout"
    android:layout_width="304dp"
    android:layout_height="match_parent"
    android:layout_gravity="left|start"
    android:fitsSystemWindows="true"
    android:background="#ffffff">
    <ListView android:id="@+id/left_drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"></ListView>
</LinearLayout>

将LinearLayout更改为您的ScrimInsetFrameLayout,如下所示。
<com.boardy.util.ScrimInsetFrameLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/linearLayout"
    android:layout_width="304dp"
    android:layout_height="match_parent"
    android:layout_gravity="left|start"
    android:fitsSystemWindows="true"
    app:insetForeground="#4000">
    <ListView android:id="@+id/left_drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"></ListView>
</com.boardy.util.ScrimInsetFrameLayout>

你好,感谢回答。我找不到OnInsetsCallback的来源,请问在哪里可以找到?先谢谢了。 - Ashokchakravarthi Nagarajan
你能否添加 ScrimInsetsView_insetForeground 属性? - reegan29
1
请使用支持库中的android.support.design.internal.ScrimInsetsFrameLayout - Roman

4

现有的解决方案已经相当过时。这里是最新的解决方案,应该可以完美地在AndroidX或Material库上运行。

  • Add android:fitsSystemWindows="true" to the root View of your layout, which happens to be DrawerLayout for your case.

    This tells the View to use the entire screen for measure & layout, overlapping with the status bar.

  • Add the following to your XML style

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

    windowTranslucentStatus will make the status bar transparent
    windowDrawsSystemBarBackgrounds tells the status bar to draw anything under it instead of being a black void.

  • Call DrawerLayout.setStatusBarBackground() or DrawerLayout.setStatusBarBackgroundColor() in your main Activity

    This tells DrawerLayout to color the status bar area.


3
我在我的项目中需要实现类似的功能。为了使我的抽屉透明,我只使用十六进制颜色透明度。使用6个十六进制数字,你有2个十六进制数字分别表示红色、绿色和蓝色的值。但如果你加入两个额外的数字(8个十六进制数字),那么你就有ARGB(两个数字表示alpha值)(看这里)。
以下是十六进制不透明度值:对于2个额外的数字。
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

例如:如果您有十六进制颜色(#111111),只需添加一个透明度值即可获得透明度。像这样:(#11111100)
我的抽屉不覆盖操作栏(就像你的一样),但在这些情况下也可以应用透明度。这是我的代码:
     <ListView
          android:id="@+id/left_drawer"
          android:layout_width="240dp"
          android:layout_height="match_parent"
          android:layout_gravity="start"
          android:background="#11111100"
          android:choiceMode="singleChoice"
          android:divider="@android:color/transparent"
          android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>

这里还有一篇文章,可以帮助您理解十六进制颜色中的 alpha 代码。


0

这里的所有答案都很复杂,让我给你一个简单明了的代码。 在你的AppTheme样式中,添加以下代码行,当你打开抽屉时,你将得到一个灰色半透明的状态栏。

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

这样就可以让它工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接