如何从首选项片段切换到Android应用程序的Dark Theme?

时间:2019-12-24 05:14:52

标签: java android android-preferences

当用户按下“首选项”时,有什么好的方法来设置“黑暗主题”? (例如Switch / CheckBoxPreference)?

我正在遵循Cannot switch between modes in DayNight theme dynamically

中Artem Mostyaev的回答

但是,由于getDelegate()recreate()是非静态方法,因此无法从我的静态设置片段中调用它们。这是我当前的首选项片段

public class SettingsActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}

public static class SettingsFragment extends PreferenceFragment{

    @Override
    public void onCreate(final Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        // ... some code...
}

// ... some function ...

还有我的preferences.xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

// ...some preferences...

<PreferenceCategory
    android:key="@string/key_util"
    android:title="@string/tittle_util">

    <CheckBoxPreference
        android:key="@string/key_theme"
        android:title="@string/tittle_theme"
        android:defaultValue="false"
        android:summary="@string/summary_theme" >

    </CheckBoxPreference>

    // ...some preferences...

</PreferenceCategory>

和styles.xml:

<resources>
<style name="AppThemeDark" parent="Theme.AppCompat.DayNight.NoActionBar">
</style>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

0 个答案:

没有答案