preferenze Initialize da XML nella principale attività [duplicato]
-
03-10-2019 - |
Domanda
Questa domanda ha già una risposta qui:
Il mio problema è che quando inizio applicazione e l'utente non ho aperto la mia PreferenceActivity
così quando ho recuperarli non si ottiene alcun valore di default definiti nel mio file preference.xml.
file preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="applicationPreference" android:title="@string/config"
>
<ListPreference
android:key="pref1"
android:defaultValue="default"
android:title="Title"
android:summary="Summary"
android:entries="@array/entry_names"
android:entryValues="@array/entry_values"
android:dialogTitle="@string/dialog_title"
/>
</PreferenceScreen>
Snippet dalla mia attività principale (metodo onCreate
):
SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pref1 = appPreferences.getString("pref1", null);
In seguito io alla fine con un valore null
.
Soluzione
In onCreate()
del vostro Activity
principale basta chiamare il metodo PreferenceManager.setDefaultValues()
.
PreferenceManager.setDefaultValues(this, R.xml.preference, false);
Questa leggerà il file preference.xml
e impostare i valori di default definiti là. Impostare l'argomento readAgain
a false
significa che questo sarà solo impostare i valori di default se questo metodo non è mai stato chiamato in passato, quindi non c'è bisogno di preoccuparsi per ignorando le impostazioni dell'utente ogni volta che viene creato il Activity
.
Altri suggerimenti
sarò breve. :)
strings.xml (in realtà ho prefs.xml in esclusiva per le preferenze):
<string name="pref_mypref_key">mypref</string>
<string name="pref_mypref_default">blah</string>
preferences.xml :
android:key="@string/pref_mypref_key"
android:defaultValue="@string/pref_mypref_default"
MyActivity.java :
String myprefVal = prefs.getString(getString(R.string.pref_mypref_key), getString(R.string.pref_mypref_default));
La chiamata alla getString()
ha null
come secondo parametro. Cambiamento che, per essere il valore di default che si desidera.