在Lollipop系统中完全透明的状态栏和导航栏

66

我正在尝试制作一个安卓启动器。我希望实现完全透明的状态栏和导航栏,这是我的主题xml文件。

<resources>
    <style name="Theme" parent="android:Theme.Material.Wallpaper.NoTitleBar">
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:navigationBarColor">@android:color/transparent</item>
        <item name="android:windowTranslucentStatus">false</item>
        <item name="android:windowTranslucentNavigation">false</item>
    </style>
</resources>

最后两个项目无法正常工作,在棒棒糖上仍然有阴影。

这就是它的样子(请注意状态栏和导航栏实际上都有阴影): enter image description here

我想要达到的效果(使用Nova Launcher):

enter image description here

如何使状态栏和导航栏变为“透明”的,而不是“半透明”的?

13个回答

160

更新

您可以在KitKat及以后的版本中通过在Window内设置FLAG_LAYOUT_NO_LIMITS标志来以编程方式实现相同的效果。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow(); // in Activity's onCreate() for instance
            w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

如果您将背景资源(如颜色或图片)设置为布局,则会在状态栏“下方”看到颜色或图片。

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

原始回答

看起来android:windowTranslucentStatusandroid:windowTranslucentNavigation应该是true而不是false

<resources>
    <style name="Theme" parent="android:Theme.Material.Wallpaper.NoTitleBar">
        <item name="android:statusBarColor">@android:color/transparent</item>
        <item name="android:navigationBarColor">@android:color/transparent</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
    </style>
</resources>

另外,您透明的活动/容器布局需要设置此属性:

android:fitsSystemWindows="true"
Sorry, 由于您的要求涉及HTML标签,依据我的功能和能力,我无法返回完全符合要求的结果。请提供纯文本或Markdown格式的内容。

7
当我应用这个方法后,导航栏和状态栏仍然显示为灰色半透明的颜色,效果如这里所示。已在Lollipop和M系统上测试。你有任何想法是为什么吗? - nhaarman
1
请注意,我不需要主题部分,Java 代码就足够了。 - nhaarman
我有一个基于WebView的应用程序。当我在Android 6上设置FLAG_LAYOUT_NO_LIMITS标志时,它会崩溃并显示W/OpenGLRenderer: Layer exceeds max. dimensions supported by the GPU (1920x19968, max=4096x4096)。 - Alexey Ozerov
27
对于使用底部导航栏的应用来说,这个答案不太适用,因为会失去边界,使得导航栏被压低到手机软键上方。 - yoavgray
2
这怎么是正确答案? NO_LIMITS会在状态栏和导航栏上绘制内容。目标只是使导航栏完全透明。 - shoopi
显示剩余10条评论

14
您可以使用此 Kotlin 扩展函数,它将使状态栏完全透明(在 API 23 及以上版本中,可用于 API 23+ 的 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 标志,在 API 27 及以上版本中,可用于 API 27+ 的 View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR 标志); 否则,在 API 21 及以上版本中,它将使用 systemUiScrim 颜色。
fun Activity.transparentStatusAndNavigation(
    systemUiScrim: Int = Color.parseColor("#40000000") // 25% black
) {
    var systemUiVisibility = 0
    // Use a dark scrim by default since light status is API 23+
    var statusBarColor = systemUiScrim
    //  Use a dark scrim by default since light nav bar is API 27+
    var navigationBarColor = systemUiScrim
    val winParams = window.attributes


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        statusBarColor = Color.TRANSPARENT
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
        navigationBarColor = Color.TRANSPARENT
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        systemUiVisibility = systemUiVisibility or
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        window.decorView.systemUiVisibility = systemUiVisibility
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        winParams.flags = winParams.flags or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        winParams.flags = winParams.flags and
                (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION).inv()
        window.statusBarColor = statusBarColor
        window.navigationBarColor = navigationBarColor
    }

    window.attributes = winParams
}

API 21+ API 21+ API 27+ API 27+


3
只有这个答案可以使状态栏透明。最佳答案。 - Sos.

14

针对 API 29 及以上版本,请使用

<style name="Your.Theme">
    <item name="android:navigationBarColor">@android:color/transparent</item>
    <item name="android:enforceNavigationBarContrast">false</item>
</style>

2
请问您能否详细说明原因? - David

9

我使用这个功能是因为它可以保持状态栏和导航栏的高度

<!-- Base application theme. -->
<style name="theme" parent="android:Theme.Material.Wallpaper.NoTitleBar">
    <item name="android:navigationBarColor">#00000000</item>
    <item name="android:statusBarColor">#00000000</item>
</style>

然而,这需要API 21+。


2
对我不起作用。你还使用哪些属性? - hamthenormal

4
你需要在你的主题中添加 android:windowDrawsSystemBarBackgrounds 标志。
<item name="android:windowDrawsSystemBarBackgrounds">true</item>

或者在 onCreate() 方法中调用此方法:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

2
这不会使导航栏透明。 - nhaarman
2
@nhaarman 你还需要添加这个。Window w = getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); - Redone
使用FLAG_LAYOUT_NO_LIMITS可以使状态栏透明,但是我的操作栏却隐藏了?你能帮忙吗? - famfamfam

4

100%可行的代码

完全透明的状态栏和导航栏

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

    initStatusNavBar();
    transparentStatusAndNavigation();

    showSystemUI();
    // hideSystemUI();

}

public static void transparentStatusAndNavigation(Activity activity) {

    Window window = activity.getWindow();

    // make full transparent statusBar
    if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
        setWindowFlag(window, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, true);
    }
    if (Build.VERSION.SDK_INT >= 19) {
        int visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        visibility = visibility | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        window.getDecorView().setSystemUiVisibility(visibility);
    }
    if (Build.VERSION.SDK_INT >= 21) {
        int windowManager = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        windowManager = windowManager | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        setWindowFlag(window, windowManager, false);
        window.setStatusBarColor(Color.TRANSPARENT);
        window.setNavigationBarColor(Color.TRANSPARENT);
    }

}

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

设置状态栏和导航栏高度和颜色:

在activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical">

    <View
        android:id="@+id/status_bg"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/primaryColorLightThemeDarkTrans"
        tools:layout_height="24dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <!--Write Code Here-->

    </LinearLayout>

    <View
        android:id="@+id/nav_bg"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/navColorLightThemeTrans"
        tools:layout_height="?actionBarSize" />
</LinearLayout>

在Java代码中:
private void initStatusNavBar() {
    int statusBarHeight = getStatusBarHeight(activity);
    int navBarHeight = getNavigationBarHeight(activity, statusBarHeight);

    View statusBarBackground = findViewById(R.id.status_bg);
    statusBarBackground.getLayoutParams().height = statusBarHeight;

    View navBarBackground = findViewById(R.id.nav_bg);
    if (Build.VERSION.SDK_INT >= 21) {
        setNavigationBarHeight(activity, navBarBackground);
    } else {
        navBarBackground.getLayoutParams().height = navBarHeight;
    }
}

public static int getStatusBarHeight(Activity activity) {
    final Resources resources = activity.getResources();
    final int resId = resources.getIdentifier("status_bar_height", "dimen", "android");
    if (resId > 0) {
        return resources.getDimensionPixelSize(resId);
    }
    return 0;
}

public static int getNavigationBarHeight(Activity activity, int statusBarHeight) {
    Point point = getNavigationBarSize(activity);
    int height = point.y;
    if (isNotchDisplay(statusBarHeight)) {
        height = height - statusBarHeight;
    }
    return height;
}

private static Point getNavigationBarSize(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Point appUsableSize = getAppUsableScreenSize(context);
        Point realScreenSize = getRealScreenSize(context);

        // navigation bar on the right
        if (appUsableSize.x < realScreenSize.x) {
            return new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y);
        }

        // navigation bar at the bottom
        if (appUsableSize.y < realScreenSize.y) {
            return new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
        }

        // navigation bar is not present
        return new Point();
    }
    return new Point();
}

private static Point getAppUsableScreenSize(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Point size = new Point();
    if (null != windowManager) {
        Display display = windowManager.getDefaultDisplay();
        display.getSize(size);
    }
    return size;
}

private static Point getRealScreenSize(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Point size = new Point();
    if (null != windowManager) {
        Display display = windowManager.getDefaultDisplay();

        if (Build.VERSION.SDK_INT >= 17) {
            display.getRealSize(size);
        } else {
            try {
                size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
                size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }

    return size;
}

private static boolean isNotchDisplay(int statusBarHeight) {
    int normalStatusBarHeight = dpToPxForNav(25);
    return statusBarHeight > normalStatusBarHeight;
}

private static int dpToPxForNav(float dp) {
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return Math.round(px);
}

public static void setNavigationBarHeight(Activity activity, View navBarBackground) {
    ViewCompat.setOnApplyWindowInsetsListener(navBarBackground, (v, insets) -> {
        int navBarHeight = insets.getSystemWindowInsetBottom();
        navBarBackground.getLayoutParams().height = navBarHeight;
        return insets.consumeSystemWindowInsets();
    });
}


@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void showSystemUI() {
    statusBarBackground.setVisibility(View.VISIBLE);
    navBarBackground.setVisibility(View.VISIBLE);
    mDecorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void hideSystemUI() {
    statusBarBackground.setVisibility(View.GONE);
    navBarBackground.setVisibility(View.GONE);
    mDecorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

styles.xml中的主题:

<style name="MyAppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">

    <!--For Notch Issues-->
    <item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="o_mr1">shortEdges</item>

    <item name="windowActionBarOverlay">true</item>

    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryDark">@color/primaryColorDark</item>
    <item name="colorAccent">@color/accentColor</item>
    <item name="colorControlHighlight">@color/colorHighlight</item>
    <item name="android:windowBackground">@android:color/white</item>
    <item name="android:textColorPrimary">#fff6d7</item>

    <item name="android:colorPrimary" tools:targetApi="lollipop">@color/primaryColor</item>
    <item name="android:colorPrimaryDark" tools:targetApi="lollipop">@color/primaryColorDark</item>
    <item name="android:statusBarColor" tools:targetApi="lollipop">@color/primaryColorDark</item>
    <item name="android:colorAccent" tools:targetApi="lollipop">@color/accentColorLight</item>
    <item name="android:colorControlHighlight" tools:targetApi="lollipop">@color/colorHighlight</item>

    <item name="android:navigationBarColor" tools:targetApi="lollipop">@color/navColor</item>

    <item name="android:windowTranslucentStatus" tools:targetApi="kitkat">true</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowTranslucentNavigation" tools:targetApi="kitkat">true</item>

</style>

在AndroidManifest.xml中:

    <activity
        android:name="com.MyActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:screenOrientation="fullSensor"
        android:theme="@style/MyAppTheme" />

3
无法在安卓9系统的Pixel 2 XL手机上运行。同时将底部软件按钮栏更改为白色栏,但不显示按钮。 - Potass
1
@Potass,你需要在Api 23+中添加标志View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR。请求状态栏以与浅色状态栏背景兼容的模式绘制。为了使其生效,窗口必须请求FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS但不是FLAG_TRANSLUCENT_STATUS。https://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 调整设置以获得所需的效果。 - Pierre
也许你需要添加window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS), 否则你的状态栏和导航栏会变成黑色。 - John

4
以下代码是我在项目中使用的示例:
styles.xml文件
<style name="FadingActionBarTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/FadingActionBarWidget</item>
</style>

<style name="FadingActionBarWidget.Transparent">
    <item name="android:background">@android:color/transparent</item>
</style>

<style name="FadingActionBarTheme.TranslucentActionBar">
    <item name="android:icon">@drawable/ic_ab_icon</item>
    <item name="android:actionBarStyle">@style/FadingActionBarWidget.Transparent</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

AndroidManifest.xml

<activity
    android:name=".MyActivity"
    android:label="@string/app_name"
    android:theme="@style/FadingActionBarTheme.TranslucentActionBar">
</activity>

1
将您的布局绘制在状态栏下:

values/styles.xml

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

values-v21/styles.xml

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

使用 CoordinatorLayout/DrawerLayout,它们已经处理了 fitsSystemWindows 参数,或者创建您自己的布局以实现以下效果:
public class FitsSystemWindowConstraintLayout extends ConstraintLayout {

    private Drawable mStatusBarBackground;
    private boolean mDrawStatusBarBackground;

    private WindowInsetsCompat mLastInsets;

    private Map<View, int[]> childsMargins = new HashMap<>();

    public FitsSystemWindowConstraintLayout(Context context) {
        this(context, null);
    }

    public FitsSystemWindowConstraintLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FitsSystemWindowConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        if (ViewCompat.getFitsSystemWindows(this)) {
            ViewCompat.setOnApplyWindowInsetsListener(this, new android.support.v4.view.OnApplyWindowInsetsListener() {
                @Override
                public WindowInsetsCompat onApplyWindowInsets(View view, WindowInsetsCompat insets) {
                    FitsSystemWindowConstraintLayout layout = (FitsSystemWindowConstraintLayout) view;
                    layout.setChildInsets(insets, insets.getSystemWindowInsetTop() > 0);
                    return insets.consumeSystemWindowInsets();
                }
            });
            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            TypedArray typedArray = context.obtainStyledAttributes(new int[]{android.R.attr.colorPrimaryDark});
            try {
                mStatusBarBackground = typedArray.getDrawable(0);
            } finally {
                typedArray.recycle();
            }
        } else {
            mStatusBarBackground = null;
        }
    }

    public void setChildInsets(WindowInsetsCompat insets, boolean draw) {
        mLastInsets = insets;
        mDrawStatusBarBackground = draw;
        setWillNotDraw(!draw && getBackground() == null);

        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                if (ViewCompat.getFitsSystemWindows(this)) {
                    ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) child.getLayoutParams();

                    if (ViewCompat.getFitsSystemWindows(child)) {
                        ViewCompat.dispatchApplyWindowInsets(child, insets);
                    } else {
                        int[] childMargins = childsMargins.get(child);
                        if (childMargins == null) {
                            childMargins = new int[]{layoutParams.leftMargin, layoutParams.topMargin, layoutParams.rightMargin, layoutParams.bottomMargin};
                            childsMargins.put(child, childMargins);
                        }
                        if (layoutParams.leftToLeft == LayoutParams.PARENT_ID) {
                            layoutParams.leftMargin = childMargins[0] + insets.getSystemWindowInsetLeft();
                        }
                        if (layoutParams.topToTop == LayoutParams.PARENT_ID) {
                            layoutParams.topMargin = childMargins[1] + insets.getSystemWindowInsetTop();
                        }
                        if (layoutParams.rightToRight == LayoutParams.PARENT_ID) {
                            layoutParams.rightMargin = childMargins[2] + insets.getSystemWindowInsetRight();
                        }
                        if (layoutParams.bottomToBottom == LayoutParams.PARENT_ID) {
                            layoutParams.bottomMargin = childMargins[3] + insets.getSystemWindowInsetBottom();
                        }
                    }
                }
            }
        }

        requestLayout();
    }

    public void setStatusBarBackground(Drawable bg) {
        mStatusBarBackground = bg;
        invalidate();
    }

    public Drawable getStatusBarBackgroundDrawable() {
        return mStatusBarBackground;
    }

    public void setStatusBarBackground(int resId) {
        mStatusBarBackground = resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null;
        invalidate();
    }

    public void setStatusBarBackgroundColor(@ColorInt int color) {
        mStatusBarBackground = new ColorDrawable(color);
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mDrawStatusBarBackground && mStatusBarBackground != null) {
            int inset = mLastInsets != null ? mLastInsets.getSystemWindowInsetTop() : 0;
            if (inset > 0) {
                mStatusBarBackground.setBounds(0, 0, getWidth(), inset);
                mStatusBarBackground.draw(canvas);
            }
        }
    }
}

main_activity.xml

<FitsSystemWindowConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fitsSystemWindows="true"
        android:scaleType="centerCrop"
        android:src="@drawable/toolbar_background"
        app:layout_constraintBottom_toBottomOf="@id/toolbar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/transparent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Content"
            android:textSize="48sp" />
    </LinearLayout>
</FitsSystemWindowConstraintLayout>

结果:

result


0

对于那些想要在KitKat及以上版本上完全透明的状态栏和导航栏的人,使用windowTranslucentNavigation与@Machado答案中的Lollipop存在一些冲突,为了避免这种冲突,需要分离样式。

styles.xml

<style name="LockScreenStyle" parent="@android:style/Theme.Wallpaper.NoTitleBar">
    <item name="android:windowTranslucentStatus" tools:targetApi="kitkat">true</item>
    <item name="android:windowTranslucentNavigation" tools:targetApi="kitkat">true</item>
</style>

styles.xml (v21)

<style name="LockScreenStyle" parent="@android:style/Theme.Wallpaper.NoTitleBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
</style>

MyClass.java

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow(); // in Activity's onCreate() for instance
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }
    }

0

这是给像我这样的新手关于Nativescript + Angular编程的建议。我开始使用 NTS市场上的一个空白模板。对于我的特定用途,我需要顶部状态栏始终透明(类似于iOS风格),并且导航栏(底部)在某些组件/模块上完全透明(不是半透明!),而在其他组件/模块中是不透明的。如果按照NTS设定的协议执行一切,您应该拥有类似于这个enter image description here的main.ts文件(我的解决方案的前提)。

我把我的工作分成了两部分,先处理顶部,再处理底部。对于顶部,我找到了这个答案,它起到了作用。所以你应该有一个看起来像这样的main.ts文件。

import { platformNativeScriptDynamic } from "@nativescript/angular";

import { AppModule } from "./app/app.module";

import * as application from "tns-core-modules/application";
import { Color } from "@nativescript/core";

platformNativeScriptDynamic().bootstrapModule(AppModule);

declare var android;

application.android.on(application.AndroidApplication.activityCreatedEvent, (event) => {

    const activity = event.activity;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    activity.getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    activity.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    activity.getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    activity.getWindow().setStatusBarColor(android.graphics.Color.TRANSPARENT);
    activity.getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);

} else {
    activity.getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    activity.getWindow().setNavigationBarColor(android.graphics.Color.TRANSPARENT);
}

const parent = activity.findViewById(android.R.id.content);
for (let i = 0; i < parent.getChildCount(); i++) {
    const childView = parent.getChildAt(i);
    if (childView instanceof android.view.ViewGroup) {
        childView.setFitsSystemWindows(true);
        childView.setClipToPadding(true);
    }
}

});

然后为导航栏添加透明度,我遵循了this并将以下代码添加到main.ts文件的第24行之前:activity.getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

需要注意的是,我们还必须尊重styles.xml文件,因此我的styles.xml文件(App_Resources\Android\src\main\res\values\styles.xml)如下所示:

    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

<!-- theme to use FOR launch screen-->
<style name="LaunchScreenThemeBase" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="toolbarStyle">@style/NativeScriptToolbarStyle</item>
    <item name="colorPrimary">@color/ns_primary</item>
    <item name="colorPrimaryDark">@color/ns_primaryDark</item>
    <item name="colorAccent">@color/ns_accent</item>
    <item name="android:windowBackground">@drawable/splash_screen</item>
    <item name="android:statusBarColor">@color/transparent</item>
</style>

<style name="LaunchScreenTheme" parent="LaunchScreenThemeBase"></style>

<!-- theme to use AFTER launch screen is loaded-->
<style name="AppThemeBase" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="toolbarStyle">@style/NativeScriptToolbarStyle</item>
    <item name="colorPrimary">@color/ns_primary</item>
    <item name="colorPrimaryDark">@color/ns_primaryDark</item>
    <item name="colorAccent">@color/ns_accent</item>
    <item name="android:statusBarColor">@color/transparent</item>
    <item name="android:navigationBarColor">@color/transparent</item>

    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:windowTranslucentNavigation">false</item>
</style>

<style name="AppTheme" parent="AppThemeBase"></style>

<!-- theme for action-bar -->
<style name="NativeScriptToolbarStyleBase" parent="Widget.AppCompat.Toolbar">
    <item name="android:background">@color/transparent</item>
    <item name="theme">@color/transparent</item>
    <item name="popupTheme">@color/transparent</item>
</style>

<style name="NativeScriptToolbarStyle" parent="NativeScriptToolbarStyleBase"></style>

花费了我大约2-3天的时间来弄清楚,希望这可以帮到你。

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