gpt4 book ai didi

java - 如何在 PreferenceFragment 中即时更新日夜模式?

转载 作者:搜寻专家 更新时间:2023-11-01 09:39:22 24 4
gpt4 key购买 nike

我见过一些像 Pocket 这样的应用程序可以在设置中立即在白天和夜间模式之间切换而无需重新加载,但我无法在我自己的示例中做到这一点:

public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
}

public static class PrefsFragment extends PreferenceFragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = getActivity();
addPreferencesFromResource(R.xml.preferences);
SwitchPreference dayNightSwitch = (SwitchPreference) findPreference(getString(R.string.pref_day_night_key));
dayNightSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isNightMode = (boolean) newValue;
AppCompatDelegate.setDefaultNightMode(isNightMode? AppCompatDelegate.MODE_NIGHT_YES:AppCompatDelegate.MODE_NIGHT_NO);
return true;
}
});
}
}
}

看起来 AppCompatDelegate.setDefaultNightModePreferenceFragmentPreferenceActivity 中根本不起作用。有什么办法可以即时更新昼夜模式吗?

最佳答案

首先,您应该调用 getActivity().recreate() 将更改应用到当前 Activity 。

但这还不够,因为我使用了 AppCompatPreferenceActivity 模板,它似乎有点不完整。我检查了 AppCompatActivity source code并找到了负责处理昼夜切换的代码。

private int mThemeId = 0;

...

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
final AppCompatDelegate delegate = getDelegate();
delegate.installViewFactory();
delegate.onCreate(savedInstanceState);
if (delegate.applyDayNight() && mThemeId != 0) {
// If DayNight has been applied, we need to re-apply the theme for
// the changes to take effect. On API 23+, we should bypass
// setTheme(), which will no-op if the theme ID is identical to the
// current theme ID.
if (Build.VERSION.SDK_INT >= 23) {
onApplyThemeResource(getTheme(), mThemeId, false);
} else {
setTheme(mThemeId);
}
}
super.onCreate(savedInstanceState);
}

@Override
public void setTheme(@StyleRes final int resid) {
super.setTheme(resid);
// Keep hold of the theme id so that we can re-set it later if needed
mThemeId = resid;
}

添加后,在首选项回调中调用 getActivity().recreate() 按预期工作。

关于java - 如何在 PreferenceFragment 中即时更新日夜模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40799202/

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