Search code examples
androidandroid-preferencespreferenceactivitypreferencepreferencescreen

Preference Screen without XML


I want to use preferences, but I don't want to use it in xml. I used this to find my xml:

this.addPreferencesFromResource(R.xml.settings);

And this is my .xml:

<PreferenceCategory android:title="name">
        <ListPreference android:key="name" android:title="Find name" android:summary="Select your name"
        android:defaultValue="2" android:entries="@array/name" android:entryValues="@array/nameValues"/>
</PreferenceCategory>

This works! But how can I do declare the preferences in my activity .java without the xml file? Maybe someone can give me a short sample code for my short code.

Thanks.


Solution

  • you just could do

    private SharedPreferences preferences;
         preferences = PreferenceManager.getDefaultSharedPreferences(this);
         Boolean mypref = preferences.getBoolean("mypref_whatever", true);   
    

    If you need to write a preference you just use an editor

        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("mypref_whatever", false);
        editor.commit();
    

    This way you don't need an xml at all. Is that what you are looking for?

    A.