如何在SwitchPreference上更改文本摘要颜色

时间:2019-02-14 03:19:42

标签: android sharedpreferences switchpreference

我使用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的Summary TextColor,它紧随当前值。 问题如下图所示 when Dark when Light

0 个答案:

没有答案