Android Pickers

Web Hosting
Android provides controls for the user to pick a time or pick a date as ready-to-use dialogs. Each picker provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year). Using these pickers helps ensure that your users can pick a time or date that is valid, formatted correctly, and adjusted to the user's locale.

We recommend that you use DialogFragment to host each time or date picker. The DialogFragment manages the dialog lifecycle for you and allows you to display the pickers in different layout configurations, such as in a basic dialog on handsets or as an embedded part of the layout on large screens.
Although DialogFragment was first added to the platform in Android 3.0 (API level 11), if your app supports versions of Android older than 3.0—even as low as Android 1.6—you can use the DialogFragment class that's available in the support library for backward compatibility.
Note: The code samples below show how to create dialogs for a time picker and date picker using the support library APIs for DialogFragment. If your app's minSdkVersion is 11 or higher, you can instead use the platform version of DialogFragment.

Creating a Time Picker


To display a TimePickerDialog using DialogFragment, you need to define a fragment class that extendsDialogFragment and return a TimePickerDialog from the fragment's onCreateDialog() method.
Note: If your app supports versions of Android older than 3.0, be sure you've set up your Android project with the support library as described in Setting Up a Project to Use a Library.

Extending DialogFragment for a time picker

To define a DialogFragment for a TimePickerDialog, you must:
Here's an example:
public static class TimePickerFragment extends DialogFragment
                            implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
    }
}
See the TimePickerDialog class for information about the constructor arguments.
Now all you need is an event that adds an instance of this fragment to your activity.

Showing the time picker

Once you've defined a DialogFragment like the one shown above, you can display the time picker by creating an instance of the DialogFragment and calling show().
For example, here's a button that, when clicked, calls a method to show the dialog:
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:text="@string/pick_time" 
    android:onClick="showTimePickerDialog" />
When the user clicks this button, the system calls the following method:
public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}
This method calls show() on a new instance of the DialogFragment defined above. The show() method requires an instance of FragmentManager and a unique tag name for the fragment.
Caution: If your app supports versions of Android lower than 3.0, be sure that you callgetSupportFragmentManager() to acquire an instance of FragmentManager. Also make sure that your activity that displays the time picker extends FragmentActivity instead of the standard Activity class.

Creating a Date Picker


Creating a DatePickerDialog is just like creating a TimePickerDialog. The only difference is the dialog you create for the fragment.
To display a DatePickerDialog using DialogFragment, you need to define a fragment class that extendsDialogFragment and return a DatePickerDialog from the fragment's onCreateDialog() method.
Note: If your app supports versions of Android older than 3.0, be sure you've set up your Android project with the support library as described in Setting Up a Project to Use a Library.

Extending DialogFragment for a date picker

To define a DialogFragment for a DatePickerDialog, you must:
Here's an example:
public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }
}
See the DatePickerDialog class for information about the constructor arguments.
Now all you need is an event that adds an instance of this fragment to your activity.

Showing the date picker

Once you've defined a DialogFragment like the one shown above, you can display the date picker by creating an instance of the DialogFragment and calling show().
For example, here's a button that, when clicked, calls a method to show the dialog:
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:text="@string/pick_date" 
    android:onClick="showDatePickerDialog" />
When the user clicks this button, the system calls the following method:
public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}
This method calls show() on a new instance of the DialogFragment defined above. The show() method requires an instance of FragmentManager and a unique tag name for the fragment.
Caution: If your app supports versions of Android lower than 3.0, be sure that you callgetSupportFragmentManager() to acquire an instance of FragmentManager. Also make sure that your activity that displays the time picker extends FragmentActivity instead of the standard Activity class.

Web Hosting

Android Spinner

Web Hosting
Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.

You can add a spinner to your layout with the Spinner object. You should usually do so in your XML layout with a <Spinner> element. For example:
<Spinner
    android:id="@+id/planets_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
To populate the spinner with a list of choices, you then need to specify a SpinnerAdapter in your Activity orFragment source code.

Populate the Spinner with User Choices


The choices you provide for the spinner can come from any source, but must be provided through anSpinnerAdapter, such as an ArrayAdapter if the choices are available in an array or a CursorAdapter if the choices are available from a database query.
For instance, if the available choices for your spinner are pre-determined, you can provide them with a string array defined in a string resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>
</resources>
With an array such as this one, you can use the following code in your Activity or Fragment to supply the spinner with the array using an instance of ArrayAdapter:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
The createFromResource() method allows you to create an ArrayAdapter from the string array. The third argument for this method is a layout resource that defines how the selected choice appears in the spinner control. The simple_spinner_item layout is provided by the platform and is the default layout you should use unless you'd like to define your own layout for the spinner's appearance.
You should then call setDropDownViewResource(int) to specify the layout the adapter should use to display the list of spinner choices (simple_spinner_dropdown_item is another standard layout defined by the platform).
Call setAdapter() to apply the adapter to your Spinner.

Responding to User Selections


When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event.
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListenerinterface and the corresponding onItemSelected() callback method. For example, here's an implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
    ...
    
    public void onItemSelected(AdapterView<?> parent, View view, 
            int pos, long id) {
        // An item was selected. You can retrieve the selected item using
        // parent.getItemAtPosition(pos)
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }
}
The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected()callback methods.
Then you need to specify the interface implementation by calling setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
If you implement the AdapterView.OnItemSelectedListener interface with your Activity or Fragment(such as in the example above), you can pass this as the interface instance.

Web Hosting

Toggle Buttons

Web Hosting
A toggle button allows the user to change a setting between two states.
You can add a basic toggle button to your layout with theToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.
Toggle buttons
Switches (in Android 4.0+)
The ToggleButton and Switch controls are subclasses ofCompoundButton and function in the same manner, so you can implement their behavior the same way.

Responding to Click Events


When the user selects a ToggleButton and Switch, the object receives an on-click event.
To define the click event handler, add the android:onClick attribute to the <ToggleButton> or <Switch>element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
For example, here's a ToggleButton with the android:onClick attribute:
<ToggleButton 
    android:id="@+id/togglebutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="Vibrate on"
    android:textOff="Vibrate off"
    android:onClick="onToggleClicked"/>
Within the Activity that hosts this layout, the following method handles the click event:
public void onToggleClicked(View view) {
    // Is the toggle on?
    boolean on = ((ToggleButton) view).isChecked();
    
    if (on) {
        // Enable vibrate
    } else {
        // Disable vibrate
    }
}
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)
Tip: If you need to change the state yourself, use the setChecked(boolean) or toggle() method to change the state.

Using an OnCheckedChangeListener

You can also declare a click event handler pragmatically rather than in an XML layout. This might be necessary if you instantiate the ToggleButton or Switch at runtime or you need to declare the click behavior in aFragment subclass.
To declare the event handler programmatically, create an CompoundButton.OnCheckedChangeListenerobject and assign it to the button by callingsetOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener). For example:
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});

Web Hosting

Android RadioButtons

Web Hosting
Radio buttons allow the user to select one option from a set. You should use radio buttons for optional sets that are mutually exclusive if you think that the user needs to see all available options side-by-side. If it's not necessary to show all options side-by-side, use aspinner instead.

To create each radio button option, create a RadioButton in your layout. However, because radio buttons are mutually exclusive, you must group them together inside a RadioGroup. By grouping them together, the system ensures that only one radio button can be selected at a time.

Responding to Click Events


When the user selects one of the radio buttons, the corresponding RadioButton object receives an on-click event.
To define the click event handler for a button, add the android:onClick attribute to the <RadioButton>element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
For example, here are a couple RadioButton objects:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton android:id="@+id/radio_pirates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/pirates"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton android:id="@+id/radio_ninjas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ninjas"
        android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Note: The RadioGroup is a subclass of LinearLayout that has a vertical orientation by default.
Within the Activity that hosts this layout, the following method handles the click event for both radio buttons:
public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
    
    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radio_pirates:
            if (checked)
                // Pirates are the best
            break;
        case R.id.radio_ninjas:
            if (checked)
                // Ninjas rule
            break;
    }
}
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)
Tip: If you need to change the radio button state yourself (such as when loading a savedCheckBoxPreference), use the setChecked(boolean) or toggle() method.

Web Hosting