Embedding ListPreference in an activity using PreferenceFragment in Android

July 7, 2012
By

ListPreference is a preference listview widget used to store a value in shared preference. The key of the ListPreference specified in the xml resource file is used to retrieve the value from the shared preference. In this article, we are creating an application which embeds a ListPreference widget in an activity using PreferenceFragment.


1. Create an Android project namely “ListPreferenceDemo”

New Android Project

Figure 1 : New Android Project


2. Select Android build target

Select Android Build Target

Figure 2 : Select Android Build Target


3. Enter application details

Enter Application Details

Figure 3 : Enter Application Details


4. res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">ListPreferenceDemo</string>

    <string name="str_lp_android_choice_title">Choose your Android Version</string>

    <string-array name="array_lp_entries">
        <item>Jelly Bean</item>
        <item>Ice Cream Sandwich</item>
        <item>Honey Comb</item>
        <item>Ginger Bread</item>
        <item>Froyo</item>
    </string-array>

    <string-array name="array_lp_entry_values">
        <item>Jelly Bean</item>
        <item>Ice Cream Sandwich</item>
        <item>Honey Comb</item>
        <item>Ginger Bread</item>
        <item>Froyo</item>
    </string-array>

</resources>

  • The elements in the array array_lp_entries is what user sees when ListPreference is opened.
  • The elements in the array array_lp_entry_values is what is stored in the shared preference.

5. res/xml/preferences.xml


<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <ListPreference
        android:key="lp_android_choice"
        android:entries="@array/array_lp_entries"
        android:entryValues="@array/array_lp_entry_values"
        android:title="@string/str_lp_android_choice_title"
    />
</PreferenceScreen>
  • PreferenceFragment uses this resource file to render the preference screen

6. res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/android_version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:layout_gravity="center_horizontal"
        android:textSize="30dp"
    />

    <fragment
        android:id="@+id/list_preference"
        android:name="in.wptrafficanalyzer.listpreferencesdemo.MyPreferenceFragment"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />

</LinearLayout>

  • The layout file for the MainActivity

7. src/in/wptrafficanalyzer/listpreferencedemo/MyPreferenceFragment.java


package in.wptrafficanalyzer.listpreferencesdemo;

import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;

public class MyPreferenceFragment extends PreferenceFragment{

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        /** Defining PreferenceChangeListener */
        OnPreferenceChangeListener onPreferenceChangeListener = new OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                OnPreferenceChangeListener listener = ( OnPreferenceChangeListener) getActivity();
                listener.onPreferenceChange(preference, newValue);
                return true;
            }
       };

        /** Getting the ListPreference from the Preference Resource */
        ListPreference p = (ListPreference ) getPreferenceManager().findPreference("lp_android_choice");
        /** Setting Preference change listener for the ListPreference */
        p.setOnPreferenceChangeListener(onPreferenceChangeListener);
    }
}

  • This is the preference fragment class which creates the list preference object from the xml  resource file res/xml/preferences.xml

8. src/in/wptrafficanalyzer/listpreferencedemo/MainActivity.java


package in.wptrafficanalyzer.listpreferencesdemo;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class MainActivity extends Activity implements OnPreferenceChangeListener {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** Getting an instance of shared preferences, that is being used in this context */
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        /** Get the value stored in the share preferences corresponding to the key "lp_android_choice" */
        String android_choice = sp.getString("lp_android_choice", "None Selected");

        /** Getting an instance of the textview object corresponds to the layout in main.xml */
        TextView tv = (TextView) findViewById(R.id.android_version);

        /** Set the value to the textview object */
        tv.setText(android_choice);

    }

    /** This method is invoked by the ListPreference on changing its value */
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        TextView tv = (TextView) findViewById(R.id.android_version);
        tv.setText(newValue.toString());
        return true;
    }

}

  • This is the MainActivity class which embeds the ListPreference widget

9. Application screenshot

ListPreferences in an Activity

Figure 4 : ListPreferences in an Activity


10. Download


11. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner