Android settings screen

Archived

This page has been archived and will receive no further updates.

note: this assumes you’ve already set up a menu with at least a Preferences/Settings option. If you haven’t, see here: android menu

  1. create a new class, extending PreferenceActivity
    public class Preferences extends PreferenceActivity {
    
  2. create res/xml/preferences.xml containing settings values you want

  3. within the onCreate method of the Preferences class, add this line to get the preferences from the XML file:
    addPreferencesFromResource(R.xml.preferences);
    
  4. add a method to the Preferences class to retrieve the values for your preferences, like this:
    public static String getDefaultLang(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context)
               .getString("defaultLang", "english");
    }
    
  5. add your new Preferences class as an Activity to AndroidManifest.xml:

    <activity android:name=".Preferences"
              android:label="@string/preferences_title"
              android:theme="@android:style/Theme">
    </activity>
    

    (here the default theme is specified to ensure the title is displayed)

  6. in your main Activity class, in the onOptionsItemSelected method, add an intent to make sure your Preferences class gets called when the user clicks the Preferences/Settings button in the menu:
    case R.id.menu_preferences:
        startActivity(new Intent(this, Preferences.class));
        return true;
    }
    
  7. lastly, call the method(s) you created in your Preferences class to retrieve the values for your preferences, in onCreate and/or elsewhere:
    defaultLang = Preferences.getDefaultLang(this);
    

to refer to a particular preference in your PreferenceActivity:

Preference somePreference = findPreference(getString(R.string.preferences_some_preference);

(the resource string you refer to is what you used as the key for the preference)