Adding Settings

Android provides a nice facility for defining what all your program preferences are and how to display them using almost no code. You define the preferences in a resource file called res/xml/settings.xml:

Download Sudokuvl/res/xml/settings.xml

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

<PreferenceScreen xmlns:android= "'"> <CheckBoxPreference android:key= "'music" android:title= "@string/music_title" android:summary="@string/music_summary" android:defaultValue= "'true" /> <CheckBoxPreference android:key= "'hints" android:title= "@string/hints_title" android:summary="@string/hints_summary" android:defaultValue= "'true" /> </PreferenceScreen>

The Sudoku program has two settings: one for background music and one for displaying hints. The keys are constant strings that will be used under the covers in Android's preferences database.

Next define the Prefs class, and make it extend PreferenceActivity:

Download Sudokuvl/src/org/example/sudoku/

package org.example.sudoku; import android.os.Bundle;

import android.preference.PreferenceActivity;

public class Prefs extends PreferenceActivity { @Override protected void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); addPreferencesFromResource(R.xml.settings);

The addPreferencesFromResource( ) method reads the settings definition from XML and inflates it into views in the current activity. All the heavy lifting takes place in the PreferenceActivity class.

Don't forget to register the Prefs activity in AndroidManifest.xml:

Download Sudokuvl/AndroidManifest.xml

<activity android:name= ". Prefs"

android:label = "@string/settings_title"> </activity>

Now rerun Sudoku, press the Menu key, select the Settings... item, and watch with amazement as the Sudoku settings page appears (see Figure 3.11, on the next page). Try changing the values there and exiting the program, and then come back in and make sure they're all still set.

Code that reads the settings and does something with them will be discussed in a different chapter (Chapter 6, Storing Local Data, on page 120). For now let's move on to the New Game button.

0 0

Post a comment