Adding Options to Sudoku

In Section 3.7, Adding a Menu, on page 64, we used the onCreateOption-sMenu() method to add a menu containing one item to the main Sudoku screen. When the user presses the Menu key and selects the Settings... item, the code starts the Prefs activity, which lets the user change the options for the game. Because Prefs extends PreferenceActivity, the values for the settings are stored in the program's preferences area, but originally we didn't do anything with them. Now we're going to implement them.

Sudoku Trivia

There are 6,670,903,752,021,072,936,960 possible classic Sudoku solution grids. If you eliminate duplicates that are just rotations, reflections, or relabelings of each other, you're left with "only" 5,472,730,538 solutions.

First let's modify the Prefs class to add a couple of getter methods that retrieve the current values of our two options. Here's the new definition:

Download Sudokuv4/src/org/example/sudoku/

package org.example.sudoku;

import android.content.Context; import android.os.Bundle;

import android.preference.PreferenceActivity; import android.preference.PreferenceManager;

public class Prefs extends PreferenceActivity { // Option names and default values private static final String OPT_MUSIC = "music"; private static final boolean OPT_MUSIC_DEF = true; private static final String OPT_HINTS = "hints"; private static final boolean OPT_HINTS_DEF = true;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings);

/** Get the current value of the music option */ public static boolean getMusic(Context context) {

return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(OPT_MUSIC, OPT_MUSIC_DEF);

/** Get the current value of the hints option */ public static boolean getHints(Context context) {

return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(OPT_HINTS, OPT_HINTS_DEF);

Be careful that the option keys (music and hints) match the keys used in res/xml/settings.xml. has to be modified to check for the music preference:

Download Sudokuv4/src/org/example/sudoku/

public static void play(Context context, int resource) { stop(context);

// Start music only if not disabled in preferences if (Prefs.getMusic(context)) {

mp = MediaPlayer.create(context, resource);


And PuzzleView.onDraw() also needs to be modified to check for the hints preference:

Download Sudokuv4/src/org/example/sudoku/

if (Prefs.getHints(getContextO)) { // Draw the hints...

If getHints( ) returns true, we draw the highlights for the hints, as shown in Figure 4.6, on page 92. Otherwise, we just skip that part.

Next I'll show you how to use the preferences API to store things other than just options.

0 0

Post a comment