【问题标题】:Toggle DayNight toggle switch to force theme切换昼夜切换开关以强制主题
【发布时间】:2019-12-28 07:27:50
【问题描述】:

我使用 android studio 的 New->Activity->Settings Activity 创建了一个偏好 Activity,我想在其中切换 Dark/Light 主题。

<EditTextPreference
    app:key="signature"
    app:title="@string/signature_title"
    app:useSimpleSummaryProvider="true" />

<ListPreference
    app:defaultValue="reply"
    app:entries="@array/reply_entries"
    app:entryValues="@array/reply_values"
    app:key="reply"
    app:title="@string/reply_title"
    app:useSimpleSummaryProvider="true" />

<SwitchPreferenceCompat
    app:key="@string/theme"
    app:title="@string/theme" />

现在,在我的主题中,我有: styles.xml

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.DayNight">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
</resources>

在连击状态下更改为暗/亮,而不是按钮状态。我怎样才能做到这一点?

我已经检查了this 问题,但很遗憾,我无法将app:id 添加到切换按钮以获取状态。

【问题讨论】:

    标签: android


    【解决方案1】:

    您需要为 see 设置 SwitchPreferenceCompat 的侦听器 然后你可以使用下面的功能来切换你的日/夜模式

      public static void toggleTheme() {
        int mode = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES;
        AppCompatDelegate.setDefaultNightMode(mode);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 1970-01-01
      • 2021-04-26
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多