Pages

Thursday, 9 June 2011

Creating an Android Preferences Screen

How do I add a preferences / setting screen to my android app?
Thankfully it is very easy to create a preferences screen, much like those you'd find within the Settings on your handset. A preference screen requires a special XML definition, you cannot use standard layouts and views, however this can still be placed within your layout folder.

The PreferenceScreen layout can be separated into sections with a PreferenceCategory which has a title and is displayed as a dividing bar o the screen. There are several preference type views:

EditTextPreference - text box entry (text string)
CheckBoxPreference - tickable check box (true/false boolean)
ListPreference - Selection from array of options (text string)
RingtonePreference - Selection of Uri of ring tones stored on device

A simple example of a preferences screen layout is shown below:

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

  <PreferenceCategory
     android:title="Options">

     <CheckBoxPreference
       android:key="pref_opt1"
       android:title="Option 1"
       android:summary="Tick to set this option"
       android:defaultValue="true"
       />
    <CheckBoxPreference
       android:key="pref_opt2"
       android:title="Option 2"
       android:summary="Tick to set this option"
       android:defaultValue="true"
       />
  </PreferenceCategory>

  <PreferenceCategory
     android:title="Selection">
      
    <ListPreference
        android:key="pref_type"
        android:title="Type"
        android:summary="Select item from array"
        android:entries="@array/types"
        android:entryValues="@array/types_values"
        android:defaultValue="1"
        />

    <EditTextPreference
        android:key="pref_text"
        android:title="Input text"
        android:summary="Tap to enter some text"
        android:dialogTitle="Enter text"
    />
     
  </PreferenceCategory>

  <Preference
    android:title="Intent"
    android:summary="Open a webpage">

    <intent
      android:action="android.intent.action.VIEW"
      android:data="http://android-elements.blogspot.com/" />

  </Preference>
   
</PreferenceScreen>

The ListPreference in the XML above references two arrays; one for the option text and one for the option values. These should be defined in your strings resource file:

/res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="types">
     <item>Type 1</item>
     <item>Type 2</item>
     <item>Type 3</item>
    </string-array>
    <string-array name="types_values">
     <item>1</item>
     <item>2</item>
     <item>3</item>
    </string-array>
</resources>

Your activity must extend the PreferenceActivity rather than a standard activity. This should be defined as below:


src/your.package.name/Prefs.java
package com.example.com;

import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.prefs);
    }   
}

Don't forget to add this activity to your manifest!
You can read and write the prefence values in code with the following method examples...

// String
    public static String Read(Context context, final String key) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        return pref.getString(key, "");
    }
 
    public static void Write(Context context, final String key, final String value) {
          SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
          SharedPreferences.Editor editor = settings.edit();
          editor.putString(key, value);
          editor.commit();        
    }
     
    // Boolean  
    public static boolean ReadBoolean(Context context, final String key, final boolean defaultValue) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        return settings.getBoolean(key, defaultValue);
    }
 
    public static void WriteBoolean(Context context, final String key, final boolean value) {
          SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
          SharedPreferences.Editor editor = settings.edit();
          editor.putBoolean(key, value);
          editor.commit();        
    }

Just as an aside, many apps I have build have been based upon a white theme rather than the default android dark. It is easy to set your preferences screen to use the built in Light theme so that it looks more consistent within your app, simply set the theme for the activity within your manifest as follows:

<activity android:name=".Prefs" android:theme="@android:style/Theme.Light">

Then your preferences screen will look something like this:

Preferences Screen (Light theme)

Please see my post on Introducing Themes for more information about themes and styles.

8 comments:

Unknown said...

Thanks

Anonymous said...

Thanks heaps, very clear. Was trying to follow another tutorial and it just kept crashing and I couldn't fix it. Yours has 1/10 as much code, easy to understand, and works perfectly!

Anonymous said...

Thumbs up!, simple and easy tutorial :)

Jack said...

Well done Dan. Great job.

Anonymous said...

Updated from 2014

- Since API 11 and above requires PreferenceFragment

http://stackoverflow.com/a/24051942/3709606

Baris said...

I think the "prefs.xml" should go to the "xml" folder and not into the "layout" folder

Unknown said...

Your posts is really helpful for me.Thanks for your wonderful post. I am very happy to read your post.


Web Designers in Chennai

Swetha said...

Nice to learn something about android preferences from this article.
electrical contractors in chennai

Post a Comment