I have a list of cities, and i want a user can choose one of these cities to add it in preferences. To do it, he goes on the CityActivity (which represents one city), open an OptionMenu and choose "Add to favorite". All the cities have a name, an ID and others fields not interesting here.
If the user add a city to its favorite (by optionsMenu => "Add to favorite"), i want that a checkbox appears in the PreferenceCategory "favorites" (already created in my PreferenceScreen, but by default empty). I will apply a specific treatment if the checkbox is checked or not (that's not the problem here).
Finally, if the user goes on the city again and selects "Remove from favorites", the checkBoxPreference which has the name of the city must disappears...
I searched for a long time on SO but never found exactly the solution at this problem...or i didn't understand.
My current sources :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="appSettings"
android:title="Préférences" >
<PreferenceCategory android:title="Accueil" >
<ListPreference
android:defaultValue="6"
android:entries="@array/nbNewsTitles"
android:entryValues="@array/nbNewsValues"
android:key="nbNews"
android:summary="Définit le nombre de news à afficher sur l'onglet d'accueil"
android:title="Nombre de news" />
</PreferenceCategory>
<PreferenceCategory android:title="Modèles" >
<ListPreference
android:entries="@array/quickTitles"
android:entryValues="@array/quickValues"
android:key="navigationRapide"
android:summary="Définit le nombre d'échéances à sauter lors de la navigation rapide"
android:title="Navigation rapide" />
</PreferenceCategory>
<PreferenceCategory android:title="Général" >
<CheckBoxPreference
android:defaultValue="false"
android:enabled="true"
android:key="doubleTapMenu"
android:summary="Affiche le menu lors d'actions spécifiques sur l'écran."
android:title="Magic Menu" />
</PreferenceCategory>
<PreferenceCategory
android:key="favoris"
android:title="Prévisions par villes" >
</PreferenceCategory>
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
You can selectively add and remove the CheckBoxPreference from your preferenceScreen.
IE
//please note that this is depreciated in new fragment based preference screens
PreferenceScreen mPreferenceScreen = getPreferenceScreen();
mPreferenceScreen.remove(mPreferenceScreen.findPreferenec("thatPreferenceKey"));
Then Add by dynamically creating the CheckBoxPreference then adding it to the perferenceScreen.
mPreferenceScreen.addPreference(yourCBP);