Come descritto in here, sottoclassi PreferenceFragment e lo visualizzo in un'attività. Questo documento spiega come ascoltare le modifiche delle preferenze here, ma solo se si sottoclasse PreferenceActivity. Dal momento che non lo sto facendo, come posso ascoltare le modifiche alle preferenze?Come ascoltare le modifiche alle preferenze all'interno di PreferenceFragment?
Ho provato a implementare OnSharedPreferenceChangeListener nel mio PreferenceFragment ma non sembra funzionare (onSharedPreferenceChanged
non sembra mai essere chiamato).
Questo è il mio codice finora:
SettingsActivity.java
public class SettingsActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
}
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener
{
public static final String KEY_PREF_EXERCISES = "pref_number_of_exercises";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
//IT NEVER GETS IN HERE!
if (key.equals(KEY_PREF_EXERCISES))
{
// Set summary to be the user-description for the selected value
Preference exercisesPref = findPreference(key);
exercisesPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:defaultValue="15"
android:enabled="true"
android:key="pref_number_of_exercises"
android:numeric="integer"
android:title="Number of exercises" />
</PreferenceScreen>
Inoltre, il PreferenceFragment è anche il posto giusto dove ascoltare le modifiche alle preferenze o devo farlo all'interno dell'attività?
Alla tua ultima domanda tutto dipende dal tuo quadro di progettazione. Usare un approccio MVC o MVP è difficile da fare con Android, ma cerco di lasciare che tutte le mie azioni abbiano luogo nell'attività (Controller) che ospita il frammento, e il frammento sia solo l'interfaccia utente (View/Presenter) –