【问题标题】:Changing the activity theme from within the fragment从片段中更改活动主题
【发布时间】:2020-02-22 21:36:50
【问题描述】:

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

<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 用于向用户打招呼“启动画面”。在MainActivityonCreate 函数中,我使用setTheme(R.style.AppTheme) 更改主题,并使用supportActionBar?.hide() 隐藏操作栏。我的应用程序是面向片段的。我只有一个 Activity 承载导航方案,它有几个片段。问题出在:

    <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)
        }
    }

这就是乐趣的开始。由于某种原因,这个空白被添加在两者之间。如果我决定注释掉这一行WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,结果会更加奇怪。状态栏变为灰色,我的ScrollView 停止工作。当我想更改活动的原始主题时,同样的错误会在几个片段中出现。我尝试从片段中更改主题,但它不起作用。在某处阅读您只能从onCreate 函数中更改活动主题。为什么我的布局行为不端?

【问题讨论】:

    标签: android android-fragments kotlin themes android-databinding


    【解决方案1】:

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

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

    所以你有两个选择:

    1. 用所述片段打开一个新活动,并将其主题设置在 安卓清单。

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

    【讨论】:

    • 那么没有其他更简洁的方法可以做到这一点?这意味着每次我想从我的片段中隐藏或显示状态栏时我都会调用 .recreate()?
    • 不幸的是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多