Android PreferenceFragment settings screen implementation

Here a basic example on how to create, store and retrieve the values from Android preferences fragment.

android preference screen

Minimum SDK version 11 is required for some controls,  for few like SwitchPreference requires API level 14 or above.

Android settings Preferences will be in XML  layout file & each attribute consists of a Key associate with it. its required to store & retrieve the data, this XML should be instantiated in preferencefragment class itself.

PreferenceCategory: Acts as heading, inside this add controls like CheckBoxPreference, ListPreference, SwitchPreference etc… refer the below xml code, (Note, this file needs to be added in XML folder under res)

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="Internet Settings">

        <SwitchPreference
            android:key="data_traffic"
            android:title="Data traffic"/>
        
        <CheckBoxPreference
            android:key="disable_internet"
            android:title="Office hours internet"
            android:summary="Functionality will disable internet from Morning 10AM to 5PM" />
        
        <Preference 
            android:title="Data usage"
            android:key="datausage"
            android:defaultValue="false"
            android:summary="Data traffic is disabled"/>

    </PreferenceCategory>

    <PreferenceCategory
        android:title="User Settings">

        <EditTextPreference
            android:key="username"
            android:title="User Name"
            android:defaultValue="User Name appears Here"
            android:summary="Enter User Name"
            android:dialogTitle="User Name" />
        
          <ListPreference
                android:key="animals_list"
                android:title="Favourite Animal"
                android:summary="%s" 
                android:defaultValue="0"
                android:entries="@array/animalsdetails"
                android:entryValues="@array/animalsvalues"
                android:dialogTitle="Choose favourite Animal" />

        </PreferenceCategory>
        

</PreferenceScreen>

To store and retrieving the values from preferences, subscribe to below event methods,

setOnPreferenceChangeListener, this will get called, if there is any change in the value, for example check box is ticked, switch button is changed, list value is selected etc…

setOnPreferenceClickListener, this will get called on click of control.

     

public class SettingsFragment extends PreferenceFragment {
	
	SharedPreferences mPrefs;
	
	 @Override
	 public void onStart(){
	     super.onStart();
	     mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
	 }

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

            // Load the preferences from an XML resource
          addPreferencesFromResource(R.xml.preferences);
            
          final Preference datausageUpdate = (Preference) findPreference("datausage");
            
          SwitchPreference InternetStatus = (SwitchPreference) findPreference("data_traffic");
            
          if (InternetStatus != null){
          //Update the operations like storing, updating UI etc... on pref change.
          InternetStatus.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                    
           @Override
           public boolean onPreferenceChange(Preference arg0, Object isdataTrafficEnabled) {
                        
           boolean isDataTrafficOn = ((Boolean) isdataTrafficEnabled).booleanValue();
                        
           Editor e = mPrefs.edit();
           e.putBoolean("data_traffic", isDataTrafficOn); 
           e.commit();
                        
           if(isDataTrafficOn)
        datausageUpdate.setSummary("Data consumption is 120 MB"); //update summary text dynamically
        else
        datausageUpdate.setSummary("Data usage is disabled");
                            
        return true;
         }
     });

            
       CheckBoxPreference disableInternet = (CheckBoxPreference)findPreference("disable_internet");
            
        if(disableInternet != null)
        {
          disableInternet.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                    
          @Override
           public boolean onPreferenceChange(Preference preference, Object checkState) {
                        
              boolean isNetToBeDisabled = ((Boolean) checkState).booleanValue();
                        
           Editor e = mPrefs.edit();
           //storing preference values & access anywhere in programme
           e.putBoolean("disable_internet", isNetToBeDisabled); 
           e.commit();
                        
            return true;
            }
        });
                
        disableInternet.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    
        @Override
        public boolean onPreferenceClick(Preference arg0) {
                    
        Toast.makeText(getActivity(), "Preference item is clicked", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
     }
            
       final EditTextPreference userName = (EditTextPreference)findPreference("username");
            
       userName.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                
       @Override
       public boolean onPreferenceChange(Preference preference, Object newValue) {
                
        String inputName = (String)newValue;
                    
        userName.setSummary(inputName);
                    
        return true;
        }
    });
}
}
          

List preference screen

ListPreference screen shown above is bit tricky, store the pre-defined key value pairs in Array and initialize in array XML like below.

(Note, array file should be added to values folder under res)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="animalsdetails">
        <item>Cat</item>
        <item>Dog</item>
        <item>Lion</item>
        <item>Tiger</item>
    </string-array>    
    
        <string-array name="animalsvalues">
        <item>0</item>
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </string-array>
</resources>

Code

            //List Preferences, 
            final ListPreference animalsList = (ListPreference) findPreference( "animals_list");
            
            if(animalsList != null)
            {
              animalsList.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                    
              @Override
              public boolean onPreferenceChange(Preference preference, Object value) {
                        
              int data = Integer.parseInt(value.toString());
                           
              //getting selected List item.
              String text    = getActivity().getResources().getStringArray(R.array.animalsdetails)[data]; 
                    
              animalsList.setSummary(text);              
          
              return true;
                    }
                });
            }