从片段中更改活动主题

问题描述 投票:0回答:1

我将首先介绍我的代码。看一下主题:

<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:windowEnableSplitTouch">false</item>
    </style>


    <style name="AppTheme.Launcher">
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:windowBackground">@drawable/launch_screen</item>
    </style>
</resources>

使用

AppTheme.Launcher,以便使用户受到“启动画面”的欢迎。在MainActivity onCreate功能中,我使用setTheme(R.style.AppTheme)更改了主题,还使用supportActionBar?.hide()隐藏了操作栏。我的应用程序是面向片段的。我只有一个活动,该活动托管具有多个片段的导航方案。问题在于:

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

在我的一个片段中,我想再次显示操作栏,并且我不希望状态栏再变得半透明,换句话说,我希望它被看到并且具有颜色PrimaryDark。为此,我在MainActivity中编写了一个函数。

    fun clearTranslucent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val w: Window = window
            w.clearFlags(
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            )
            w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        }
    }

Weird status bar behavior

这是乐趣的开始。出于某种原因,该空白之间添加了空格。如果我决定对此行WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS进行注释,结果将更加奇怪。状态栏变为灰色,并且我的ScrollView停止工作。当我想更改活动的原始主题时,也会在几个片段中遇到相同的错误。我尝试从片段中更改主题,但是它不起作用。在只能从onCreate功能内更改活动主题的地方阅读。为什么我的布局行为不正确?

android android-fragments kotlin themes android-databinding
1个回答
1
投票

您正在描述的问题是已知的错误。

您只能在活动的onCreate发生之前设置活动的主题

所以您有两个选择:

  1. 用所述片段打开一个新活动,并在android清单。

  2. 在片段内设置活动的主题,并在更改后在oncreate中编写逻辑以显示片段主题,调用activity.recreate()进行活动重新启动自身,从而应用您的主题。

© www.soinside.com 2019 - 2024. All rights reserved.