假设您的PreferenceActivity 中有一个CheckboxPreference,声明为:
<CheckBoxPreference
android:defaultValue="false"
android:key="prefAutoLogin"
android:summary="@string/pref_autologin_summary"
android:title="@string/pref_autologin" />
在您的主要活动的onOptionsItemSelected 中,您检查按下了哪个菜单项,如果是设置菜单,则启动您的PreferenceActivity:
final Intent i = new Intent(this, MySettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
// RESULT_SETTINGS is an integer constant to identify the preference activity
您为结果启动MySettingsActivity,这意味着当前活动将在onActivityResult 方法中返回时得到通知。您覆盖该方法以检查修改:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case RESULT_SETTINGS:
// here you check whether the auto-login preference was checked or not:
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
final boolean autoLoginChecked = prefs.getBoolean("prefAutoLogin", false);
// prefAutoLogin is the key of your CheckBoxPreference declared in the xml above.
if (autoLoginChecked)
{
// perform the actions necessary when the checkbox is ticked
}
else
{
// ...
}
break;
}
[...]
default {...}
}
如果您仅在复选框从 false 勾选为 true 时才需要执行某些操作(而不是每次从 pref.activity 以选中状态返回时),您应该在启动首选项活动之前存储其状态,并在返回时匹配新状态:
private boolean initiallyChecked;
在您开始设置活动之前:
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
initiallyChecked = prefs.getBoolean("prefAutoLogin", false);
那么当activity返回时,你不只是检查checkbox的值是否为真,而是检查之前是否为假:
if (autoLoginChecked && !initiallyChecked)
{ .... }
更多参考请参见this post on viralpatel。