Android Programming Tutorials

(Romina) #1
What's Your Preference?

This sets up a single-item PreferenceScreen. Note that it references two


string arrays, one for the display labels of the sort-order selection list, and


one for the values actually stored in the SharedPreferences.


So, to define those string arrays, add a LunchList/res/values/arrays.xml file


with the following content:


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="sort_names">
<item>By Name, Ascending</item>
<item>By Name, Descending</item>
<item>By Type</item>
<item>By Address, Ascending</item>
<item>By Address, Descending</item>
</string-array>
<string-array name="sort_clauses">
<item>name ASC</item>
<item>name DESC</item>
<item>type, name ASC</item>
<item>address ASC</item>
<item>address DESC</item>
</string-array>
</resources>

Note we are saying that the value stored in the SharedPreferences will


actually be an ORDER BY clause for use in our SQL query. This is a convenient


trick, though it does tend to make the system a bit more fragile – if we


change our column names, we might have to change our preferences to


match and deal with older invalid preference values.


Step #2: Create the Preference Activity.............................................


Next, we need to create a PreferenceActivity that will actually use these


preferences. To do this, add a PreferenceActivity implementation, stored as


LunchList/src/apt/tutorial/EditPreferences.java:


package apt.tutorial;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceActivity;

public class EditPreferences extends PreferenceActivity {

136
Free download pdf