2

我通过使用创建了一个设置PreferenceFragmentCompat

public class SettingsFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle bundle, String s) {
            addPreferencesFromResource(R.xml.settings_pref);

        Preference pref = findPreference("theme_key");
        SwitchPreference swPref = (SwitchPreference) pref;

        pref.setOnPreferenceChangeListener((preference, o) -> {
            boolean state = Boolean.valueOf(o.toString());
            String summaryValue;
            if(state){
                summaryValue = swPref.getSwitchTextOn().toString();
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                restartActivity();
            }else {
                summaryValue = swPref.getSwitchTextOff().toString();
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                restartActivity();
            }
            Toast.makeText(getContext(), "Theme " + summaryValue, Toast.LENGTH_SHORT).show();
            return true;
        });
    }

    private void restartActivity() {
        Intent i = new Intent(getActivity(), SettingsActivity.class);
        startActivity(i);
        getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        getActivity().finish();
    } }

我的 xml 文件(settings_pref)如下所示:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <SwitchPreference
        android:key="theme_key"
        android:defaultValue="false"
        android:title="@string/title_theme_pref"
        android:summaryOn="Dark"
        android:summaryOff="Light"
        android:textColor="?attr/textcolor"<!--this textColor not working, i have test with different color based on theme, still has no effect-->
        android:textColorHint="?attr/textcolor" />
</PreferenceScreen>

作为功​​能它工作正常,但我仍然没有找到改变我的 SwitchPreference 的摘要 TextColor 的文献,它遵循当前值。问题如下图所示 天黑的时候 当光

4

0 回答 0