Let's assume you have a CheckboxPreference
in your PreferenceActivity
declared as:
<CheckBoxPreference
android:defaultValue="false"
android:key="prefAutoLogin"
android:summary="@string/pref_autologin_summary"
android:title="@string/pref_autologin" />
In your main activity's onOptionsItemSelected
you check which menu item was pressed, and in case of the settings menu, you start your PreferenceActivity
:
final Intent i = new Intent(this, MySettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
// RESULT_SETTINGS is an integer constant to identify the preference activity
You start the MySettingsActivity
for result, meaning the current activity will be notified when it returns in the onActivityResult
method. You overwrite that method to check for the modifications:
@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 {...}
}
If you need to perform some actions only when the checkbox was ticked from false to true (and not every time it returns from the pref. activity with a checked state), you should store its state prior to start the preference activity, and match against the new state on return:
private boolean initiallyChecked;
and before you start the settings activity:
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
initiallyChecked = prefs.getBoolean("prefAutoLogin", false);
Then when the activity returns back, you don't just check if the checkbox value is true, but check to see whether it was false before:
if (autoLoginChecked && !initiallyChecked)
{ .... }
For more reference see this post on viralpatel.