使用自定义工具栏时如何使状态栏透明?

时间:2018-09-12 17:56:07

标签: android statusbar

使用以下代码,我可以使状态栏完全透明:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);

public static void setWindowFlag(Activity activity, final int bits, boolean on) {
    Window win = activity.getWindow();
    WindowManager.LayoutParams winParams = win.getAttributes();
    if (on) {
        winParams.flags |= bits;
    } else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

使用上面的代码,状态栏和操作栏都变得透明,但是之后,我使用Drawer Layout实现了Navigation Drawer。

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<android.support.constraint.ConstraintLayout
    android:id="@+id/content_constraint"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/red_background">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

</android.support.constraint.ConstraintLayout>

<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/drawer_view"/>

实现导航抽屉后,由于此代码仍在工作,因此操作栏仍然透明:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

但是状态栏透明度停止工作:

setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);

我认为这是由于新的工具栏取代了默认的Actionbar而导致的,因此本应在默认actionbar上运行的代码在修改后的代码上不起作用。如何解决?

0 个答案:

没有答案