正在从另一个 activity 更新首选项 UI 实例?

Updating Preference UI instance from another activity?

如何从另一个 activity(主要 Activity)更新我在设置 Activity 中创建的 Prefence UI 实例?

我尝试在 Main Activity 中使用这些行来更新设置 Activity 中的首选项,但我得到 ClassCastException

Preference IsFeature =(Preference)((PreferenceActivity)context).findPreference((getString(R.string.key_enable_feature)));
IsFeature.setEnabled(True);

只是想知道是否有其他方法可以做到这一点?

任何帮助、反馈或答案都将非常有用!

你可以试试这个:

在设置的 xml 中,从要更改的元素中获取 "key" 属性(在底部示例中,它是 "example_switch")。比将此代码放在按钮的 onClick 方法或其他任何您想要的地方。下面这个在一般设置中采用 switch 的首选项并将其值设置为 false。

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("example_switch", false); // "example_switch" - "key" attribute of your element | false - value
editor.commit();