2011-09-08 34 views
10

Ho provato a impostare il valore predefinito per ListPreference ma non viene visualizzato nulla.Valore predefinito ListPreference non visualizzato

Potete controllare il mio codice per eventuali errori?

Grazie.

In verità, Emad

Questo è nel file settings.xml:

<PreferenceCategory android:title="Media:"> 
    <CheckBoxPreference android:key="ChimeWhenMusicIsPlaying" 
     android:title="@string/ChimeWhenMusicIsPlayingTitle" android:summary="@string/ChimeWhenMusicIsPlayingSummary" 
     android:defaultValue="false" /> 

    <ListPreference android:title="Chime Volume" 
     android:key="ChimeVolume" android:summary="Select volume for the chiming sound." 
     android:entries="@array/chimeVolumeLabels" android:entryValues="@array/chimeVolumeValues" 
     android:defaultValue="1" /> 

</PreferenceCategory> 

Questo è nel file array:

<resources> 

    <string-array name="chimeVolumeLabels"> 
    <item>Default</item> 
    <item>Soft</item> 
    <item>Medium</item> 
    <item>Loud</item> 
    </string-array> 

    <string-array name="chimeVolumeValues"> 
    <item>1</item> 
    <item>2</item> 
    <item>3</item> 
    <item>4</item> 
    </string-array> 
</resources> 

risposta

27

Ho scoperto che a volte ho bisogno di cancellare i dati dell'applicazione. Disinstallare e reinstallare l'app. Dopodiché, tutto funziona come previsto.

+0

hai salvato ore della mia vita. – akashr

+0

comportamento strano, grazie – speedDeveloper

+1

Questo potrebbe essere dovuto al fatto che Android imposterà i valori predefiniti solo ** una volta ** - vedi [questo] (https://developer.android.com/reference/android/preference/PreferenceManager .html # setDefaultValues ​​(android.content.Context,% 20int,% 20boolean)) –

10

ho scoperto che devo chiamare PreferenceManager .setDefaultValues ​​() nella mia attività Preferenze in modo che il valore predefinito venga visualizzato inizialmente.

public class PreferencesActivity extends PreferenceActivity { 

    @Override 
    protected void onCreate (Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // This static call will reset default values only on the first ever read 
     PreferenceManager.setDefaultValues(getBaseContext(), R.xml.settings, false); 

     addPreferencesFromResource(R.xml.settings); 
    } 
} 
+2

+1 per questa risposta. Fino a quando l'attività delle preferenze non viene invocata per la prima volta dopo l'installazione dell'applicazione, la chiamata a * sharedPreferences.getString (key, null) * restituirà null anche se l'attributo * android: defaultValue * è impostato in xml. Se i valori delle preferenze predefinite devono essere disponibili prima che l'attività delle preferenze venga richiamata nell'applicazione per la prima volta, la chiamata a PreferenceManager.setDefaultValues ​​() è un'ottima soluzione. – pavel

Problemi correlati