Preferences widgets

Here are a few details about some of the widgets you may want to use on your preferences activity. The milestone 3 description already has an example of a CheckBox. This covers the SeekBar (slider), EditText, and the most difficult one: radio buttons.

SeekBar

The SeekBar is a way to provide a slider. It’s relatively simple, the position of the slider corresponds to an integer. You can set the property max to the maximum possible value. The minimum value is zero.

// Given a SeekBar, you get and set its value like this:
SeekBar sb = (SeekBar) findViewById(R.id.volumeSlider);
sb.getProgress();  // returns current value as int
sb.setProgress(42); // sets current value to int

EditText

The EditText lets the user type something. Touching it should reveal the keyboard. You will probably want to clear out the text property, so the field starts out blank. But then it can be difficult for the user to understand what is expected in that text box, so instead provide a hint property, such as “Your name.” The hint is there until the user touches it, and then their value can be typed.

// Given an EditText box, you can get and set its value:
EditText txt = (EditText) findViewById(R.id.nameText);
txt.getText(); // returns current value as String
txt.setText("Anonymous");

RadioGroup

This is the most complex. To get the expected mutually-exclusive behavior, you will want to contain your RadioButtons within a RadioGroup. You can find the RadioGroup in the palette on the right, in the section “Containers” (underneath “Widgets”).

You probably want one of these radio buttons to be the default. Just turn on its checked property.

To retrieve the value from the Activity code:

RadioGroup difficultyRG = findViewById(R.id.difficultyRadio);
int difficultyID = difficultyRG.getCheckedRadioButton();

This method returns the resource ID of the button that is checked. That is, difficultyID will be equal to either R.id.easyButton, or R.id.mediumButton, or R.id.difficultButton.

To set the selected button, it seems that you can’t do it in the RadioGroup. Instead, you refer to the button directly:

RadioButton mediumB = findViewById(R.id.mediumButton);
mediumB.setChecked(true);

The group will take care of turning off the other buttons besides the one that is set to checked.