Android10Input

advertisement
Android 10: Input Controls
Kirk Scott
1
•
•
•
•
The Great Crested Grebe
(Old World)
What you’ve probably seen in Anchorage:
The Red-Necked Grebe
2
3
4
5
6
•
•
•
•
•
•
•
•
•
•
These are the sections in this unit:
10.1 Introduction
10.2 Input Controls
10.3 Buttons
10.4 Text Fields
10.5 Checkboxes
10.6 Radio Buttons
10.7 Toggle Buttons
10.8 Spinners
10.10 Pickers
7
10.1 Introduction
8
• The overall goal of this unit is to provide
material for the second half of the second
homework assignment
• You can pick from among the topics in this set
of overheads for items to get points for on the
assignment
• The depth of coverage is intended to give you
an entry point into the API so that you can
learn the specifics that you need
9
• As usual, the contents of the overheads
consist largely of material taken from the
online tutorials, with occasional commentary
by me
• The commentary will either be introduced as
commentary or appear in square brackets
• If not set off in this way, the content is taken
from the tutorials
10
10.2 Input Controls
11
• Input Controls
• Input controls are the interactive components
in your app's user interface.
• Android provides a wide variety of controls
you can use in your UI, such as buttons, text
fields, seek bars, checkboxes, zoom buttons,
toggle buttons, and many more.
12
13
• Adding an input control to your UI is as simple
as adding an XML element to your XML layout.
• For example, here's a layout with a text field
and button:
• [See the following overhead.
• If they show this again I’ll either have to cry or
stop copying it…]
14
• <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/
android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
15
• Each input control supports a specific set of
input events so you can handle events such as
when the user enters text or touches a button.
• [This bland statement is actually of some
consequence.
• It touches on the topic of event handling.
• We’ve seen that with buttons and
sendMessage(), but it’s a much broader topic.]
16
• Common Controls
• Here's a list of some common controls that
you can use in your app.
• Follow the links to learn more about using
each one.
• [On the overheads following the next one.]
17
• Note:
• Android provides several more controls than
are listed here.
• Browse the android.widget package to
discover more.
• If your app requires a specific kind of input
control, you can build your own custom
components.
18
Control Type
Description
Related Classes
Button
A push-button that can be
pressed, or clicked, by the
user to perform an action.
Button
Text field
An editable text field. You
can use the
AutoCompleteTextView
widget to create a text
entry widget that provides
auto-complete suggestions
EditText,
AutoCompleteTextView
Checkbox
An on/off switch that can
be toggled by the user. You
should use checkboxes
when presenting users with CheckBox
a group of selectable
options that are not
mutually exclusive.
19
Control Type
Description
Related Classes
Radio button
Similar to checkboxes, except that
RadioGroup
only one option can be selected
RadioButton
in the group.
Toggle button
An on/off button with a light
indicator.
Spinner
A drop-down list that allows users
Spinner
to select one value from a set.
Pickers
A dialog for users to select a
single value for a set by using
up/down buttons or via a swipe
gesture. Use a DatePickercode>
widget to enter the values for the
date (month, day, year) or a
DatePicker, TimePicker
TimePicker widget to enter the
values for a time (hour, minute,
AM/PM), which will be formatted
automatically for the user's
locale.
ToggleButton
20
10.3 Buttons
21
• 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:
22
• With text, using the Button class:
• <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
... />
23
• With an icon, using the ImageButton class:
• <ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_icon"
... />
24
• 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"
... />
25
• 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.
26
• 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 layout with a button
using android:onClick:
27
• <?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" />
28
• 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
}
29
• 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)
30
• Using an OnClickListener
• You can also declare the click event handler
pragmatically 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.
• [Notice the two conditions:
• Either you’re creating the button at run time,
• Or you’re coding with fragments.]
31
• To declare the event handler
programmatically, create an
View.OnClickListener object and assign it to
the button by calling
setOnClickListener(View.OnClickListener).
• For example:
• [Wait. See the following overheads.]
32
• [Before going further with the tutorial
presentation, it’s worthwhile to review
anonymous inner classes and listeners
• Consider the code on the following overhead,
taken from the CSCE 202 overheads]
33
•
•
•
•
•
•
•
•
•
•
ActionListener myListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String inputString = myField.getText();
myOutputPanel.setString(inputString);
myField.setText(“”);
myOutputPanel.repaint();
}
};
34
• [A call is made to construct an instance of a class
that implements the ActionListener interface.
• The definition of the class immediately follows
the call to the constructor, and is part of the same
line of code.
• The critical element of the class definition is the
one method, actionPerformed(), which is the
method declared in the listener interface.
• The code defines an anonymous inner class which
implements the listener interface and the object
which is constructed is an instance of it.]
35
• [Now consider the code shown on the following
overhead, which is the next thing in the tutorials
• It doesn’t create a button
• It uses one defined in XML
• It uses an anonymous listener
• It is one step deeper than the previous code
• The listener object is constructed inside the
parentheses for the setOnClickListener() method]
36
•
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
}
});
37
• [This code creates an anonymous inner class
which implements the View.OnClickListener
interface.
• Note that I double checked the Android API,
and this is an interface.
• There are other, similar interfaces, like
DialogInterface.OnClickListener.
• The critical and familiar method in the listener
definition is the onClick() method.]
38
• 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.
• [Note that the next two overheads actually give
an insight into using themes and styles rather
than information on specific attributes of buttons
that can be set.]
39
• You can control exactly how your controls are
styled using a theme that you apply to your entire
application.
• 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.
40
• 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.
41
• 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:
42
• <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" />
43
• 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.
44
• [It could be a simple bitmap or color, but they
want to show something a little more
interesting, a state list.]
• You can define the state list in an XML file that
defines three different images or colors to use
for the different button states.
45
• 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.
46
• 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.10.png
• button_pressed.10.png
• button_focused.10.png.
47
• 3. Create a new XML file in the res/drawable/
directory (name it something like
button_custom.xml).
• Insert the following XML:
48
•
<?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>
• [Notice the kinds of tags, selector and item
• This is the syntax for a state list
• Stay tuned to see how you connect it to a button]
49
• 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).
50
• 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.
51
• 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.
• 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:
52
•
<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"
/>
53
• For more information about this XML syntax,
including how to define a disabled, hovered,
or other button states, read about State List
Drawable.
54
10.4 Text Fields
55
• Text Fields
• 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.
56
• 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 an <EditText> element.
57
58
• Specifying the Keyboard Type
• 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.
59
• Figure 1. The default text input type.
60
• Figure 2. The textEmailAddress input type.
61
• Figure 3. The phone input type.
62
• 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.
63
• "textUri" Normal text keyboard with the /
character.
• "number" Basic number keypad.
• "phone" Phone-style keypad.
64
• 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.
65
• Here are some of the common input type
values that define keyboard behaviors:
• "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.
66
• "textAutoCorrect" Normal text keyboard that
corrects commonly misspelled words.
• "textPassword" Normal text keyboard, but the
characters entered turn into dots.
• "textMultiLine" Normal text keyboard that
allows users to input long strings of text that
include line breaks (carriage returns).
67
• For example, here's how you can collect a
postal address, capitalize each word, and
disable text suggestions:
• <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" />
68
• All behaviors are also listed with the
android:inputType documentation.
69
• 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."
70
• Figure 4. If you declare
android:imeOptions="actionSend", the
keyboard includes the Send action.
71
• You can specify the action by setting the
android:imeOptions attribute.
• For example, here's how you can specify the
Send action:
72
• <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" />
73
• 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 (@code
actionNext} action to the current EditText so
the user can select Next to move to the next
field.
74
• 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.
75
• 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.
• For example, here's how you can listen for when the
user clicks the Send button on the keyboard:
76
•
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;
}
});
77
• 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.
• You can customize the text of this button by
setting the android:imeActionLabel attribute:
78
• <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" />
79
• Figure 5. A custom action label with
android:imeActionLabel.
80
• 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.
81
• [The presentation order is a little strange
• They now refer back to figure 5 to contrast it with
figure 6]
• 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.
82
• Figure 6. The fullscreen text field ("extract
mode") is disabled with
android:imeOptions="flagNoExtractUi".
83
• 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 (@link android.widget.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.
84
• Figure 7. Example of AutoCompleteTextView
with text suggestions.
85
• The following procedure describes how to set
up an AutoCompleteTextView that provides
suggestions from an array, using
ArrayAdapter:
86
• 1. Add the AutoCompleteTextView to your
layout. Here's a layout with only the text field:
•
• <?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" />
87
•
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):
•
<?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>
88
• 3. In your Activity or Fragment, use the
following code to specify the adapter that
supplies the suggestions:
•
// 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);
89
• 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().
90
10.5 Checkboxes
91
• 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.
92
• 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.
93
• 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.
94
• 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 CheckBox
objects in a list:
95
• <?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>
96
• Within the Activity that hosts this layout, the
following method handles the click event for
both checkboxes:
97
•
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
}
98
• 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.
99
10.6 Radio Buttons
100
• 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.
101
102
• 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.
103
• 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.
104
• 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:
105
• <?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>
106
• 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:
107
• 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;
}
108
• 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.
109
10.7 Toggle Buttons
110
• 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.
111
• Toggle buttons
Switches (in Android 4.0+)
• The ToggleButton and Switch controls are
subclasses of CompoundButton and function in
the same manner, so you can implement their
behavior the same way.
112
• 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.
113
• 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:
114
• <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"/>
115
• 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
}
116
• 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.
117
• 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 a
Fragment subclass.
118
• To declare the event handler
programmatically, create an
CompoundButton.OnCheckedChangeListener
object and assign it to the button by calling
setOnCheckedChangeListener(CompoundButt
on.OnCheckedChangeListener).
• For example:
119
• 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
}
}
});
120
10.8 Spinners
121
• 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.
122
123
• 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 or
Fragment source code.
124
• Populate the Spinner with User Choices
• The choices you provide for the spinner can come
from any source, but must be provided through a
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:
125
• <?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>
126
• 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:
127
•
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);
128
• 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.
129
• 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.
130
• 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:
131
•
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
}
}
132
• 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);
133
• 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.
134
10.10 Pickers
135
• 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.
136
137
• 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.
138
• 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.
139
• 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.
140
• 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:
141
•
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
}
}
142
• 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.
143
• 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:
144
• <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_time"
android:onClick="showTimePickerDialog"
/>
145
• 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");
}
146
• 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 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.
147
• 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.
• 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.
148
• 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:
149
•
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
}
}
150
• 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.
151
• 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:
152
• <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_date"
android:onClick="showDatePickerDialog"
/>
153
• When the user clicks this button, the system
calls the following method:
• public void showDatePickerDialog(View v) {
DialogFragment newFragment = new
DatePickerFragment();
newFragment.show(getSupportFragmentManage
r(), "datePicker");
}
154
• 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 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.
155
Summary and Mission
• This unit contained items that you can choose
from when deciding what you want to do for
part 2 of the second assignment.
• When choosing what to do, keep in mind what
you might be thinking about doing for your
final project
• It might be convenient to learn how to do
something as part of HW 2 and then apply
that knowledge in your project
156
The End
157
Download