我已经在Implementing user choice of theme中尝试了答案,但它对我不起作用。
我的设置中有一个列表首选项,允许用户在浅色或深色主题之间进行选择。我该怎么办?这是我在“设置活动”中的OnPreferenceChangeListener,我是从互联网上学到的。
private static Preference.OnPreferenceChangeListener themelistener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
if (preference instanceof ListPreference) { //set ListPreference summary
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
if (index == 0) {
Toast.makeText(thisActivity, "Dark" , Toast.LENGTH_SHORT).show();MainActivity.reloadTheme(); //if done toast will be deleted
} else if (index == 1){Toast.makeText(thisActivity, "Light" , Toast.LENGTH_SHORT).show();MainActivity.reloadTheme();
}
return true;
}
return true;
}
;
};
修改 我的MainActivity代码段有问题,无法解析themeId
public static void reloadTheme()
{
int index = PreferenceManager.getDefaultSharedPreferences(thisActivity).getInt("index", 0);
if(index == 0){ //couldn't resolve themeId
themeId = R.style.OwnDark;
}
else if(index == 1){
themeId = R.style.OwnLight;
}
}