gpt4 book ai didi

java - SharedPreferences 如何与 UpdateUI 配合?

转载 作者:行者123 更新时间:2023-12-02 03:15:12 27 4
gpt4 key购买 nike

我是开发 Android 应用程序的菜鸟。我想问一下。我的 PreferenceActivity 如何希望在不返回 MainActivity 并再次转到 PreferenceActivity 的情况下更新。在此,我提供了一些功能来更改 PreferenceActivity 的主题。这是我的 PreferenceActivity:

公共(public)类SettingsPreference扩展了PreferenceActivity{

SwitchPreference themeSwitch;
String myPref = "preferences";
SharedPreferences.Editor editor;
String summary;
int theme;

@Override
public void onCreate(Bundle savedInstanceState)
{
// TODO: Implement this method
final SharedPreferences.Editor editor = getSharedPreferences(myPref, MODE_PRIVATE).edit();

final SharedPreferences prefs = getSharedPreferences(myPref, MODE_PRIVATE);
final String summary = prefs.getString("stringSummary", "Default theme");
final int theme = prefs.getInt("intTheme", (android.R.style.Theme_DeviceDefault_Light));

setTheme(theme);

super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_preference);

themeSwitch = (SwitchPreference) findPreference("switchTheme");
themeSwitch.setSummary(summary);

if (themeSwitch != null) {
themeSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference arg0, Object isOnObject) {
boolean isThemeOn = (Boolean) isOnObject;
if (isThemeOn) {
Toast.makeText(SettingsPreference.this, "Theme Dark ON", Toast.LENGTH_SHORT).show();
editor.putString("stringSummary", "Theme Dark ON");
editor.putInt("intTheme", (android.R.style.Theme_DeviceDefault));
editor.apply();
themeSwitch.setSummary(summary);

} else {
Toast.makeText(SettingsPreference.this, "Theme Dark OFF", Toast.LENGTH_SHORT).show();
editor.putString("stringSummary", "Theme Dark OFF");
editor.putInt("intTheme", (android.R.style.Theme_DeviceDefault_Light));
editor.apply();
themeSwitch.setSummary(summary);

}
return true;
}
});
}
}

}

最佳答案

如果您更改了 Activity 布局,则只需重新启动它即可。尝试将其添加到 onPreferenceChange() 的末尾。

如果您使用的是 API11+,请调用 Activity。

this.recreate();

否则,我们只需完成该 Activity 并以相同的 Intent 重新开始它即可。

Intent intent = getIntent();
finish();
startActivity(intent);

关于java - SharedPreferences 如何与 UpdateUI 配合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40430077/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com