Reputation: 6526
I have ListPreference which I want to use it for enable/disable multiple preferences which are all under PreferencesScreen/PreferencesCategory (in same activity), so how to do that in one shot?
is there an easy way to disable or enable a grouped preferences depending on ListPreference value in another PreferenceScreen or PreferenceCategory ?
I am using eclipse, however, similar steps are existed in android studio.
after finish click, if any errors appears recompile the project from menu: project -> clean .
now the created project have settings and we can call it by add two lines in MainActivity.java in onOptionsItemSelected method to be like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent i = new Intent (this, SettingsActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
run the app and click on settings in action bar to open settings activity
finally the settings will appears, and contains 3 preferences screens as following:
look at "add friends to messages" it is in pref_general, what I want is when user change it's value to "never" the all preferences under pref_data_sync should be disabled, while if the new value is "always" then all preferences in pref_notification should disabled otherwise enable all preferences in both screen preferences.
Upvotes: 1
Views: 1406
Reputation: 5186
1.) You implement a OnSharedPreferenceChangeListener
in your SettingsActivity.java
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
//override this method
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key)
{
}
}
2.) Now check in this method for the value of "add friends" preference.
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
//override this method
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key)
{
String add_friends = PreferenceManager.getDefaultSharedPreferences(context).getString(
"add_friends", null);
if(add_friends.equalsIgnoreCase("never")
{
// Get the screen you want to remove
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("pref_screen");
//remove the other screens.
PreferenceGroup preferenceScreenParent = getParent(preferenceScreen);
preferenceScreenParent.removePreference(preferenceScreen);
}
}
}
Upvotes: 1