gpt4 book ai didi

android - 调用 onSharedPreferenceChanged 后重启应用程序

转载 作者:行者123 更新时间:2023-11-29 15:10:54 24 4
gpt4 key购买 nike

onSharedPreferenceChanged调用后如何重启应用?

ActivityPreferences.java:

[..]
public static class FragmentPreferences extends PreferenceFragment {
private Context context;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences);

final SharedPreferences sp = context.getSharedPreferences("PREFERENCE_KEY", Context.MODE_PRIVATE);
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
context.finish();
startActivity(new Intent(ActivityPreferences.this, ActivityLogin.class));
}
};
}
}

这就是我的尝试,但我无法调用 finish()

我想更改主题,如果列表首选项 s1_theme 已设置为亮/暗:

ActivityMain.java:

@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = getApplicationContext();
final SharedPreferences sp = context.getSharedPreferences("PREFERENCE_KEY", Context.MODE_PRIVATE);
if (sp.getString("s1_theme", "-1") == "light"){
setTheme(R.style.AppTheme_BaseLight);
} else {
setTheme(R.style.AppTheme_BaseDark);
}
setContentView(R.layout.activity_main);
[..]

最佳答案

尝试这段代码...这将重新启动 MainActivity...

                    this.finish();
Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh);

使用此代码在 MainActivity 中创建一个方法,并通过传递上下文从您要重新启动的 fragment 类中调用此方法...

关于android - 调用 onSharedPreferenceChanged 后重启应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31654048/

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