Android - creating a custom preferences activity screen

Android applications can maintain their own internal preferences (and allow them to be modified by users) with very little coding. In fact, you don't even need to write an code to explicitly save these preferences, it's all handled automatically!

Create a new Android project, with an intial activity title Main.

Create two more activities:

  1. ShowPrefs, which extends Activity
  2. Set Prefs, which extends PreferenceActivity

Add these two to your AndroidManifest.xml file:

<activity android:name=".SetPrefs"></activity>
<activity android:name=".ShowPrefs"></activity>

Now we'll work on fleshing out each activity. First, open up the main.xml layout file and add a couple of buttons to it:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
<Button android:text="Edit Preferences"
   android:id="@+id/prefButton"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center_horizontal"/>
<Button android:text="Show Preferences"
   android:id="@+id/showButton"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center_horizontal"/>
</LinearLayout>

Next, create a couple button listeners in Main.java to handle the clicks and start the other activities:

Button editPrefs = (Button) findViewById(R.id.prefButton);
      editPrefs.setOnClickListener(new View.OnClickListener() {
             public void onClick(View view) {
                 Intent myIntent = new Intent(view.getContext(), SetPrefs.class);
                 startActivityForResult(myIntent, 0);
             }

     });
    
     Button showPrefs = (Button) findViewById(R.id.showButton);
     showPrefs.setOnClickListener(new View.OnClickListener() {
             public void onClick(View view) {
                 Intent myIntent = new Intent(view.getContext(), ShowPrefs.class);
                 startActivityForResult(myIntent, 0);
             }

     });

Now, we'll create the actual preferences layout. You'll need to create a file called preferences.xml inside res/xml, and you'll likely have to create the xml directory as well. Add the following xml:

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

First we'll add a category, which is just a way to group similar preferences... sort of a horizontal bar. Add this inside the PreferenceScreen tags:

<PreferenceCategory android:title="First Category">
</PreferenceCategory>

Now add a Checkbox and an Edittext box (inside the PreferenceCategory tags):

<CheckBoxPreference
   android:key="checkboxPref"
   android:title="Checkbox Preference"
   android:summary="This preference can be true or false"
   android:defaultValue="false"/>

<EditTextPreference
   android:key="editTextPref"
   android:title="EditText Preference"
   android:summary="This allows you to enter a string"
   android:defaultValue="Nothing"/>

The key is how you will refer to the preference in code, the title is the large text that will be displayed, and the summary is the smaller text (this will make sense when you see it).

Let's say we've got a second group of preferences that apply to a different part of the app. Add a new category just below the first one:

<PreferenceCategory android:title="Second Category">
</PreferenceCategory>

In there we'll a list with radio buttons, so add:

<ListPreference
   android:key="listPref"
   android:title="List Preference"
   android:summary="This preference lets you select an item in a array"
   android:entries="@array/listArray"
   android:entryValues="@array/listValues" />

When complete, your full xml file should look like this:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
 <PreferenceCategory android:title="First Category">
<CheckBoxPreference
   android:key="checkboxPref"
   android:title="Checkbox Preference"
   android:summary="This preference can be true or false"
   android:defaultValue="false"/>
<EditTextPreference
   android:key="editTextPref"
   android:title="EditText Preference"
   android:summary="This allows you to enter a string"
   android:defaultValue="Nothing"/>
 </PreferenceCategory>
 <PreferenceCategory android:title="Second Category">
  <ListPreference
   android:key="listPref"
   android:title="List Preference"
   android:summary="This preference lets you select an item in a array"
   android:entries="@array/listArray"
   android:entryValues="@array/listValues" />
 </PreferenceCategory>
</PreferenceScreen>

However, when you try to save it, you'll get an error because you're missing your array definition. To fix this, add a file called arrays.xml in res/values, and paste in the following:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string-array name="listArray">
     <item>Value 1</item>
     <item>Value 2</item>
     <item>Value 3</item>
 </string-array>
 <string-array name="listValues">
     <item>1</item>
     <item>2</item>
     <item>3</item>
 </string-array>
</resources>

Finally (for the preferences screen at least...) add the code that will display the preferences layout to the SetPrefs.java file:

 @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     addPreferencesFromResource(R.xml.preferences);
     }

OK, so now we've got an activity that will set preferences, and save them without the need to write custom save code. Let's throw together an activity to work with the saved preferences. Create a new layout called showpreferences.xml and give it three Textviews:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView 
 android:id="@+id/textview1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="textview1"/>
<TextView 
 android:id="@+id/textview2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="textview2"/>
<TextView 
 android:id="@+id/textview3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="textview3"/>
</LinearLayout>

Open up the ShowPrefs.java file and have it use that layout:

setContentView(R.layout.showpreferences);

Then add the following code to load the DefaultSharedPreferences and display them:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  
TextView text1 = (TextView)findViewById(R.id.textview1);
TextView text2 = (TextView)findViewById(R.id.textview2);
TextView text3 = (TextView)findViewById(R.id.textview3);
  
text1.setText(new Boolean(prefs.getBoolean("checkboxPref", false)).toString());
text2.setText(prefs.getString("editTextPref", "<unset>"));;
text3.setText(prefs.getString("listPref", "<unset>"));

Fire up the application in the emulator and click the Edit Preferences button. Set various things, click the back button, then the Edit Preferences button again. Notice that your choices have been saved.


 

Now click the Show Preferences button, and you should see the results of what you set:


 

There are two more preference types that I did not include here:

  • RingtonePreference - shows a radioGroup that lists your ringtones
  • PreferenceScreen - allows you to embed a second preference screen inside the first - it opens up a new set of preferences when clicked

Print | posted @ Friday, December 3, 2010 5:27 PM

Comments on this entry:

Gravatar # re: Android - creating a custom preferences activity screen
by pele at 12/21/2010 4:39 PM

The title of this article seems a bit misleading to me. What you are describing is how to create a 'standard' preference screen using the built in API. To me, a 'custom' preference would be an html page with a backend to sqlite (or whatever interface with the data manually managed). The existing preferences leave A LOT to be desired and so I'm searching for an example of someone who has made a 'truly' custom preference for their application. Wouldn't happen to have run across something like that would you?

Otherwise, nice write-up. Clear and to the point.
Gravatar # re: Android - creating a custom preferences activity screen
by Ashish at 1/8/2011 10:13 AM

Hats off!!! to you man..
Gr8 tutorial. Very nicely wrapped up the things..
Gravatar # re: Android - creating a custom preferences activity screen
by whitetiger at 2/8/2011 10:02 AM

simply the best tutorial in the internet for beginners on android preferences..thanks a lot..was really helpful.
Gravatar # re: Android - creating a custom preferences activity screen
by whitetiger at 2/8/2011 10:07 AM

expect more such tutorials from u..can u make a tutorial with such clear explanations on "creating preferences using codes" rather than xml..so that 1 is able to create his own flexible preference settings/menu..for example the built in android edittext preference takes only strings..one may need to take integer..float values from the user..
Gravatar # re: Android - creating a custom preferences activity screen
by Bill at 2/8/2011 4:13 PM

Take a look at the android:inputType and android:digits XML Attributes (http://developer.android.com/reference/android/widget/TextView.html) - seems like they should be able to accomplish what you need...
Gravatar # re: Android - creating a custom preferences activity screen
by whitetiger at 2/9/2011 3:33 AM

Hi Bill,
i got the solution just changed the type from string to int with parseInt...thx
Gravatar # re: Android - creating a custom preferences activity screen
by silver_mx at 6/13/2011 3:15 AM

Nice job, you saved me a lot of time, thanks so much!!
Gravatar # re: Android - creating a custom preferences activity screen
by roj at 8/16/2011 11:38 PM

frndz plz help me..
i have followed this tutorial..and theres no error in my code..but wen running code in emulator..it shows "the application has stopped unexpectedly"..
plz help me..watz the reason for it???
Gravatar # re: Android - creating a custom preferences activity screen
by Richard at 10/6/2011 8:04 AM

It is nearly impossible to read the font on this page.
The color and font selection makes it extremely hard to read.
Gravatar # re: Android - creating a custom preferences activity screen
by arslan at 2/7/2012 8:01 AM

can u please tell me if i have already data in my projet and we want to retrieve into string accepts strings item ? How ??
Gravatar # re: Android - creating a custom preferences activity screen
by kalandar at 3/12/2012 1:33 AM

Amazing tutorial friend
thank you so much......
Gravatar # re: Android - creating a custom preferences activity screen
by gonzalo at 5/3/2012 8:59 AM

great tutorial!!!

thanks!!!!!
Post A Comment
Title:
Name:
Email:
Comment:
Verification: