Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Android 12: Input Controls
Kirk Scott
1
2
3
4
Introduction
5
Outline
•
•
•
•
•
•
•
12.1
12.2
12.3
12.4
12.5
12.6
12.7
Buttons
Text Fields
Checkboxes
Radio Buttons
Toggle Buttons
Spinners
Pickers
6
12.1 Buttons
7
Buttons
• A button consists of text or an icon (or both
text and an icon) that communicates what
action occurs when the user touches it.
• Depending on whether you want a button
with text, an icon, or both, you can create the
button in your layout in three ways:
8
With text, using the Button class:
• <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
... />
9
With an icon, using the ImageButton
class:
• <ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_icon"
... />
10
With text and an icon, using the Button class
with the android:drawableLeft attribute:
• <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:drawableLeft="@drawable/button_icon"
... />
11
Responding to Click Events
• When the user clicks a button, the Button
object receives an on-click event.
• To define the click event handler for a button,
add the android:onClick attribute to the
<Button> 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.
12
• The Activity hosting the layout must then
implement the corresponding method.
• For example, here's a layout with a button
using android:onClick:
• [See the following overhead]
13
•
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
14
• Within the Activity that hosts this layout, the
following method handles the click event:
•
/** Called when the user touches the button */
public void sendMessage(View view) {
// Do something in response to button click
}
15
• 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)
16
Using an OnClickListener
• You can also declare the click event handler
programmatically rather than in an XML
layout.
• This might be necessary if you instantiate the
Button at runtime or you need to declare the
click behavior in a Fragment subclass.
17
• To declare the event handler
programmatically, create an
View.OnClickListener object and assign it to
the button by calling
setOnClickListener(View.OnClickListener).
• For example:
• [See the following overhead]
18
Commentary plus tutorial code
• [The syntax you’re seeing in this example is for an anonymous
inner class—a listener for an event
• The onClick() method of the onClickListener is defined ‘inline’
• This kind of syntax works for cases where you will never need
to refer to listener object again]
•
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
19
Styling Your Button
• The appearance of your button (background
image and font) may vary from one device to
another, because devices by different
manufacturers often have different default
styles for input controls.
• You can control exactly how your controls are
styled using a theme that you apply to your
entire application.
20
• For instance, to ensure that all devices running
Android 4.0 and higher use the Holo theme in
your app, declare
android:theme="@android:style/Theme.Holo"
in your manifest's <application> element.
• Also read the blog post, Holo Everywhere for
information about using the Holo theme while
supporting older devices.
21
• To customize individual buttons with a different
background, specify the android:background
attribute with a drawable or color resource.
• Alternatively, you can apply a style for the button,
which works in a manner similar to HTML styles
to define multiple style properties such as the
background, font, size, and others.
• For more information about applying styles, see
Styles and Themes.
22
Borderless button
• One design that can be useful is a "borderless"
button.
• Borderless buttons resemble basic buttons except
that they have no borders or background but still
change appearance during different states, such
as when clicked.
• To create a borderless button, apply the
borderlessButtonStyle style to the button.
• For example:
• [See the following overhead]
23
•
<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
style="?android:attr/borderlessButtonStyle" />
24
Custom background
• If you want to truly redefine the appearance of
your button, you can specify a custom
background.
• Instead of supplying a simple bitmap or color,
however, your background should be a state list
resource that changes appearance depending on
the button's current state.
• You can define the state list in an XML file that
defines three different images or colors to use for
the different button states.
25
• To create a state list drawable for your button
background:
• 1. Create three bitmaps for the button
background that represent the default,
pressed, and focused button states.
• To ensure that your images fit buttons of
various sizes, create the bitmaps as Ninepatch bitmaps.
26
• 2. Place the bitmaps into the res/drawable/
directory of your project.
• Be sure each bitmap is named properly to
reflect the button state that they each
represent, such as button_default.9.png,
button_pressed.9.png, and
button_focused.9.png.
27
• 3. Create a new XML file in the res/drawable/
directory (name it something like
button_custom.xml).
• Insert the following XML:
• [See the following overhead]
28
•
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused"
android:state_focused="true" />
<item android:drawable="@drawable/button_default" />
</selector>
29
• This defines a single drawable resource, which
will change its image based on the current state
of the button.
• The first <item> defines the bitmap to use when
the button is pressed (activated).
• The second <item> defines the bitmap to use
when the button is focused (when the button is
highlighted using the trackball or directional pad).
• The third <item> defines the bitmap to use when
the button is in the default state (it's neither
pressed nor focused).
30
• Note: The order of the <item> elements is
important.
• When this drawable is referenced, the <item>
elements are traversed in-order to determine
which one is appropriate for the current button
state.
• Because the default bitmap is last, it is only
applied when the conditions
android:state_pressed and android:state_focused
have both evaluated as false.
31
• This XML file now represents a single
drawable resource and when referenced by a
Button for its background, the image
displayed will change based on these three
states.
• 4. Then simply apply the drawable XML file as
the button background:
• [See the following overhead]
32
•
<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
android:background="@drawable/button_custom"
/>
33
• For more information about this XML syntax,
including how to define a disabled, hovered,
or other button states, read about State List
Drawable.
34
12.2 Text Fields
35
Text Fields
36
• A text field allows the user to type text into
your app.
• It can be either single line or multi-line.
• Touching a text field places the cursor and
automatically displays the keyboard.
37
• In addition to typing, text fields allow for a
variety of other activities, such as text
selection (cut, copy, paste) and data look-up
via auto-completion.
• You can add a text field to you layout with the
EditText object. You should usually do so in
your XML layout with a <EditText> element.
38
Specifying the Keyboard Type
39
Figure 1. The default text input type.
40
Figure 2. The textEmailAddress input
type.
41
Figure 3. The phone input type.
42
• Text fields can have different input types, such
as number, date, password, or email address.
• The type determines what kind of characters
are allowed inside the field, and may prompt
the virtual keyboard to optimize its layout for
frequently used characters.
43
• You can specify the type of keyboard you want
for your EditText object with the
android:inputType attribute.
• For example, if you want the user to input an
email address, you should use the
textEmailAddress input type:
• [See the following overhead]
44
•
<EditText
android:id="@+id/email_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/email_hint"
android:inputType="textEmailAddress" />
45
• There are several different input types
available for different situations.
• Here are some of the more common values
for android:inputType:
• "text"
• Normal text keyboard.
• "textEmailAddress"
• Normal text keyboard with the @ character.
46
•
•
•
•
•
•
"textUri"
Normal text keyboard with the / character.
"number"
Basic number keypad.
"phone"
Phone-style keypad.
47
Controlling other behaviors
• The android:inputType also allows you to specify
certain keyboard behaviors, such as whether to
capitalize all new words or use features like autocomplete and spelling suggestions.
• The android:inputType attribute allows bitwise
combinations so you can specify both a keyboard
layout and one or more behaviors at once.
• Here are some of the common input type values
that define keyboard behaviors:
• [See the following overheads]
48
• "textCapSentences"
• Normal text keyboard that capitalizes the first
letter for each new sentence.
• "textCapWords"
• Normal text keyboard that capitalizes every word.
• Good for titles or person names.
• "textAutoCorrect"
• Normal text keyboard that corrects commonly
misspelled words.
49
• "textPassword"
• Normal text keyboard, but the characters entered turn
into dots.
• "textMultiLine"
• Normal text keyboard that allow users to input long
strings of text that include line breaks (carriage
returns).
• For example, here's how you can collect a postal
address, capitalize each word, and disable text
suggestions:
• [See the following overhead]
50
•
<EditText
android:id="@+id/postal_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/postal_address_hint"
android:inputType="textPostalAddress|
textCapWords|
textNoSuggestions" />
51
• All behaviors are also listed with the
android:inputType documentation.
52
Specifying Keyboard Actions
• In addition to changing the keyboard's input
type, Android allows you to specify an action
to be made when users have completed their
input.
• The action specifies the button that appears in
place of the carriage return key and the action
to be made, such as "Search" or "Send."
53
Figure 4. If you declare
android:imeOptions="actionSend", the
keyboard includes the Send action.
54
• You can specify the action by setting the
android:imeOptions attribute.
• For example, here's how you can specify the
Send action:
• [See the following overhead]
55
• <EditText
android:id="@+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/search_hint"
android:inputType="text"
android:imeOptions="actionSend" />
56
• If you do not explicitly specify an input action
then the system attempts to determine if
there are any subsequent android:focusable
fields.
• If any focusable fields are found following this
one, the system applies the "actionNext"
action to the current EditText so the user can
select Next to move to the next field.
57
• If there's no subsequent focusable field, the
system applies the "actionDone" action.
• You can override this by setting the
android:imeOptions attribute to any other
value such as "actionSend" or "actionSearch"
or suppress the default behavior by using the
"actionNone" action.
58
Responding to action button events
• If you have specified a keyboard action for the
input method using android:imeOptions attribute
(such as "actionSend"), you can listen for the
specific action event using an
TextView.OnEditorActionListener.
• The TextView.OnEditorActionListener interface
provides a callback method called
onEditorAction() that indicates the action type
invoked with an action ID such as
IME_ACTION_SEND or IME_ACTION_SEARCH.
59
• For example, here's how you can listen for
when the user clicks the Send button on the
keyboard:
• [See the following overhead
• Notice that the tutorials consistently use the
anonymous inner class/listener syntax]
60
•
EditText editText = (EditText)
findViewById(R.id.search);
editText.setOnEditorActionListener(new
OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int
actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
sendMessage();
handled = true;
}
return handled;
}
});
61
Setting a custom action button label
• If the keyboard is too large to reasonably
share space with the underlying application
(such as when a handset device is in
landscape orientation) then fullscreen
("extract mode") is triggered.
• In this mode, a labeled action button is
displayed next to the input.
62
Figure 5. A custom action label with
android:imeActionLabel.
63
• You can customize the text of this button by
setting the android:imeActionLabel attribute:
• [See the following overhead]
64
•
<EditText
android:id="@+id/launch_codes"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/enter_launch_codes"
android:inputType="number"
android:imeActionLabel="@string/launch" />
65
Adding Other Keyboard Flags
• In addition to the actions you can specify with
the android:imeOptions attribute, you can add
additional flags to specify other keyboard
behaviors.
• All available flags are listed along with the
actions in the android:imeOptions
documentation.
66
• For example, figure 5 shows how the system
enables a fullscreen text field when a handset
device is in landscape orientation (or the
screen space is otherwise constrained for
space).
• You can disable the fullscreen input mode
with flagNoExtractUi in the
android:imeOptions attribute, as shown in
figure 6.
67
Figure 6. The fullscreen text field ("extract
mode") is disabled with
android:imeOptions="flagNoExtractUi"
68
Providing Auto-complete Suggestions
• If you want to provide suggestions to users as
they type, you can use a subclass of EditText
called AutoCompleteTextView.
• To implement auto-complete, you must
specify an Adapter that provides the text
suggestions.
• There are several kinds of adapters available,
depending on where the data is coming from,
such as from a database or an array.
69
Figure 7. Example of AutoCompleteTextView
with text suggestions.
70
• The following procedure describes how to set
up an AutoCompleteTextView that provides
suggestions from an array, using
ArrayAdapter:
• 1. Add the AutoCompleteTextView to your
layout.
• Here's a layout with only the text field:
• [See the following overhead]
71
•
<?xml version="1.0" encoding="utf-8"?>
<AutoCompleteTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/autocomplete_country"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
72
• 2. Define the array that contains all text
suggestions.
• For example, here's an array of country names
that's defined in an XML resource file
(res/values/strings.xml):
• [See the following overhead]
73
• <?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="countries_array">
<item>Afghanistan</item>
<item>Albania</item>
<item>Algeria</item>
<item>American Samoa</item>
<item>Andorra</item>
<item>Angola</item>
<item>Anguilla</item>
<item>Antarctica</item>
...
</string-array>
</resources>
74
• 3. In your Activity or Fragment, use the
following code to specify the adapter that
supplies the suggestions:
• [See the following overhead]
75
•
// Get a reference to the AutoCompleteTextView in the layout
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.autocomplete_country);
// Get the string array
String[] countries =
getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, countries);
textView.setAdapter(adapter);
76
• Here, a new ArrayAdapter is initialized to bind
each item in the COUNTRIES string array to a
TextView that exists in the simple_list_item_1
layout (this is a layout provided by Android
that provides a standard appearance for text
in a list).
• Then assign the adapter to the
AutoCompleteTextView by calling
setAdapter().
77
12.3 Checkboxes
78
Checkboxes
• Checkboxes allow the user to select one or
more options from a set.
• Typically, you should present each checkbox
option in a vertical list.
79
80
• To create each checkbox option, create a
CheckBox in your layout.
• Because a set of checkbox options allows the
user to select multiple items, each checkbox is
managed separately and you must register a
click listener for each one.
81
Responding to Click Events
• When the user selects a checkbox, the
CheckBox object receives an on-click event.
• To define the click event handler for a
checkbox, add the android:onClick attribute to
the <CheckBox> 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.
82
• The Activity hosting the layout must then
implement the corresponding method.
• For example, here are a couple CheckBox
objects in a list:
• [See the following overhead]
83
• <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/
android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox_meat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/meat"
android:onClick="onCheckboxClicked"/>
<CheckBox android:id="@+id/checkbox_cheese"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cheese"
android:onClick="onCheckboxClicked"/>
</LinearLayout>
84
• Within the Activity that hosts this layout, the
following method handles the click event for
both checkboxes:
• [See the following overhead]
85
•
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
}
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_meat:
if (checked)
// Put some meat on the sandwich
else
// Remove the meat
break;
case R.id.checkbox_cheese:
if (checked)
// Cheese me
else
// I'm lactose intolerant
break;
// TODO: Veggie sandwich
}
86
• 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 checkbox state yourself
(such as when loading a saved CheckBoxPreference),
use the setChecked(boolean) or toggle() method.
87
12.4 Radio Buttons
88
Radio Buttons
• 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 sideby-side, use a spinner instead.
89
90
• 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.
91
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.
92
• The Activity hosting the layout must then
implement the corresponding method.
• For example, here are a couple RadioButton
objects:
• [See the following overhead]
93
• <?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>
94
• 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:
• [See the following overhead]
95
• 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;
}
96
• 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 saved
CheckBoxPreference), use the setChecked(boolean) or
toggle() method.
97
12.5 Toggle Buttons
98
Toggle Buttons
• A toggle button allows the user to change a setting
between two states.
• You can add a basic toggle button to your layout with
the ToggleButton 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.
• SwitchCompat is a version of the Switch widget which
runs on devices back to API 7.
• If you need to change a button's state yourself, you can
use the CompoundButton.setChecked() or
CompoundButton.toggle() methods.
99
• Toggle buttons
• Switches (in Android 4.0+)
100
Responding to Button Presses
• To detect when the user activates the button
or switch, create an
CompoundButton.OnCheckedChangeListener
object and assign it to the button by calling
setOnCheckedChangeListener().
• For example:
• [See the following overhead]
101
• 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
}
}
});
102
12.6 Spinners
103
Spinners
• 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.
104
105
• 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:
• [See the following overhead]
106
• <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 or Fragment
source code.
107
Populate the Spinner with User
Choices
• The choices you provide for the spinner can come
from any source, but must be provided through
an SpinnerAdapter, 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:
• [See the following overhead]
108
• <?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>
109
• 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:
• [See the following overhead]
110
•
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);
111
• 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.
112
• 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.
113
Responding to User Selections
• When the user selects an item from the dropdown, the Spinner object receives an on-itemselected event.
• To define the selection event handler for a
spinner, implement the
AdapterView.OnItemSelectedListener interface
and the corresponding onItemSelected() callback
method.
• For example, here's an implementation of the
interface in an Activity:
• [See the following overhead]
114
•
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
}
}
115
• The AdapterView.OnItemSelectedListener
requires the onItemSelected() and
onNothingSelected() callback methods.
• Then you need to specify the interface
implementation by calling
setOnItemSelectedListener():
• [See the following overhead]
116
•
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.
117
12.7 Pickers
118
Pickers
• 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.
119
120
• 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.
121
• 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.
122
Creating a Time Picker
• To display a TimePickerDialog using
DialogFragment, you need to define a fragment
class that extends DialogFragment 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.
123
Extending DialogFragment for a time
picker
• To define a DialogFragment for a
TimePickerDialog, you must:
• Define the onCreateDialog() method to return an
instance of TimePickerDialog
• Implement the
TimePickerDialog.OnTimeSetListener interface to
receive a callback when the user sets the time.
• Here's an example:
• [See the following overhead]
124
•
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);
minute,
}
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour,
DateFormat.is24HourFormat(getActivity()));
public void onTimeSet(TimePicker view, int hourOfDay, int
minute) {
// Do something with the time chosen by the user
}
}
125
• 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.
126
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:
• [See the following overhead]
127
• <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_time"
android:onClick="showTimePickerDialog"
/>
128
• 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");
}
129
• 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.
130
• Caution: If your app supports versions of
Android lower than 3.0, be sure that you call
getSupportFragmentManager() 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.
131
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 extends DialogFragment
and return a DatePickerDialog from the
fragment's onCreateDialog() method.
132
Extending DialogFragment for a date
picker
• To define a DialogFragment for a
DatePickerDialog, you must:
• Define the onCreateDialog() method to return an
instance of DatePickerDialog
• Implement the
DatePickerDialog.OnDateSetListener interface to
receive a callback when the user sets the date.
• Here's an example:
• [See the following overhead]
133
•
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
}
}
134
• 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.
135
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:
• [See the following overhead]
136
• <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_date"
android:onClick="showDatePickerDialog"
/>
137
• 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.
138
Summary and Mission
• There is no specific mission for this set of
overheads
• It is reasonable to assume that this unit
covered some of the most likely candidates for
features that you will include as part of
assignment 3
139
The End
140