Android 9: Input Controls

Post on 25-Feb-2016

56 Views

Category:

Documents

5 Downloads

Preview:

Click to see full reader

DESCRIPTION

Android 9: Input Controls. Kirk Scott. The Great Crested Grebe (Old World) What you’ve probably seen in Anchorage: The Red-Necked Grebe. These are the sections in this unit: 9.1 Introduction 9.2 Input Controls 9.3 Buttons 9.4 Text Fields 9.5 Checkboxes 9.6 Radio Buttons - PowerPoint PPT Presentation

Transcript

1

Android 9: Input Controls

Kirk Scott

2

• The Great Crested Grebe• (Old World)• What you’ve probably seen in Anchorage:• The Red-Necked Grebe

3

4

5

6

7

• These are the sections in this unit:• 9.1 Introduction• 9.2 Input Controls• 9.3 Buttons• 9.4 Text Fields• 9.5 Checkboxes• 9.6 Radio Buttons• 9.7 Toggle Buttons• 9.8 Spinners• 9.9 Pickers

8

9.1 Introduction

9

• As usual, the decision to present this material at this point is based partially on background ideas found in the book

• 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

• As mentioned before, what you’re getting is an idiosyncratic path through some of the various topics covered in the tutorials

• The goal is to cover enough of the items involved in sufficient depth so that the perceptive learner could pick up more when needed

11

• The more immediate goal 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

12

9.2 Input Controls

13

• 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.

14

15

• 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…]

16

• <?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>

17

• 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.]

18

• 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.]

19

• 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.

20

Control Type Description Related Classes

ButtonA 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 a group of selectable options that are not mutually exclusive.

CheckBox

21

Radio buttonSimilar to checkboxes, except that only one option can be selected in the group.

RadioGroup RadioButton

Toggle button An on/off button with a light indicator. ToggleButton

Spinner A drop-down list that allows users to select one value from a set. Spinner

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 TimePicker widget to enter the values for a time (hour, minute, AM/PM), which will be formatted automatically for the user's locale.

DatePicker, TimePicker

Control Type Description Related Classes

22

9.3 Buttons

23

• 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:

24

• With text, using the Button class:

• <Button    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/button_text"    ... />

25

• With an icon, using the ImageButton class:

• <ImageButton    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:src="@drawable/button_icon"    ... />

26

• 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"    ... />

27

• 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.

28

• 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:

29

• <?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" />

30

• 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}

31

• 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)

32

• 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.]

33

• 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.• First we’ll have a stroll down memory lane on

anonymous inner classes and listeners.]

34

• [Consider the code on the following overhead, taken from the CSCE 202 overheads.

• A call is made to construct an instance of a class that implements the ActionListener interface.

• The definition of the class immediately follows the constructor, and is part of the same line of code.

• The critical element of the class definition is the one method, which is the listener method, which is declared in the interface.

• The code defines an anonymous inner class and the listener object is an instance of it.]

35

• ActionListener myListener = new ActionListener()• {• public void actionPerformed(ActionEvent event)• {• String inputString = myField.getText();• myOutputPanel.setString(inputString);• myField.setText(“”);• myOutputPanel.repaint();• }• };

36

• [Now consider the shown on the overhead following the next one, which is the next thing in the tutorials.

• It doesn’t create a button.• It uses one defined in XML.

37

• It creates an anonymous inner class which implements the View.OnClickListener interface.

• The critical method is the onClick() method.• Note that I double checked the Android API,

and this is an interface.• There are other, similar interfaces, like

DialogInterface.OnClickListener.]

38

• 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    }});

39

• 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.]

40

• 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.

41

• 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.

42

• 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:

43

• <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" />

44

• 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.

45

• [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.

46

• 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 Nine-patch bitmaps.

47

• 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.

48

• 3. Create a new XML file in the res/drawable/ directory (name it something like button_custom.xml).

• Insert the following XML:

49

• <?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 tags, selector and item.]

50

• 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).

51

• 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.

52

• 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:

53

• <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"  />

54

• For more information about this XML syntax, including how to define a disabled, hovered, or other button states, read about State List Drawable.

55

9.4 Text Fields

56

• 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. • 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.

57

• [Can you believe they didn’t edit andcorrect this?]

• 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.

• [The picture on the following overhead is nice, but uninformative…]

58

59

• 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.

60

• Figure 1. The default text input type.

61

• Figure 2. The textEmailAddress input type.

62

• Figure 3. The phone input type.

63

• 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.

64

• "textUri" Normal text keyboard with the / character.

• "number" Basic number keypad. • "phone" Phone-style keypad.

65

• 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 auto-complete 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.

66

• 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.

67

• "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 allow users to input long strings of text that include line breaks (carriage returns).

68

• 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" />

69

• All behaviors are also listed with the android:inputType documentation.

70

• 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."

71

• Figure 4. If you declare android:imeOptions="actionSend", the keyboard includes the Send action.

72

• You can specify the action by setting the android:imeOptions attribute.

• For example, here's how you can specify the Send action:

73

• <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" />

74

• 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.

75

• 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.

76

• 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:

77

• 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;    }});

78

• 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:

79

• <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" />

80

• Figure 5. A custom action label with android:imeActionLabel.

81

• 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.

82

• 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.

83

• Figure 6. The fullscreen text field ("extract mode") is disabled with android:imeOptions="flagNoExtractUi".

84

• 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.

85

• Figure 7. Example of AutoCompleteTextView with text suggestions.

86

• The following procedure describes how to set up an AutoCompleteTextView that provides suggestions from an array, using ArrayAdapter:

87

• 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" />

88

• 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>

89

• 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 layoutAutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);// Get the string arrayString[] 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);

90

• 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().

91

9.5 Checkboxes

92

• 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.

93

• 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.

94

• 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.

95

• 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:

96

• <?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>

97

• Within the Activity that hosts this layout, the following method handles the click event for both checkboxes:

98

• 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    }}

100

9.6 Radio Buttons

101

• 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 side-by-side, use a spinner instead.

102

103

• 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.

104

• 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.

105

• 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:

106

• <?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>

107

• 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:

108

• 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;    }}

110

9.7 Toggle Buttons

111

• 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.

112

• 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.

113

• 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.

114

• 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:

115

• <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"/>

116

• 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    }}

117

• 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.

118

• 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.

120

• 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        }    }});

121

9.8 Spinners

122

• 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.

123

124

• 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.

125

• 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:

126

• <?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>

127

• 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:

128

• Spinner spinner = (Spinner) findViewById(R.id.spinner);// Create an ArrayAdapter using the string array and a default spinner layoutArrayAdapter<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 appearsadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);// Apply the adapter to the spinnerspinner.setAdapter(adapter);

129

• 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.

131

• 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.OnItemSelectedListener interface and the corresponding onItemSelected() callback method.

• For example, here's an implementation of the interface in an Activity:

132

• 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    }}

134

• 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.

135

9.9 Pickers

136

• 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.

137

138

• 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.

139

• 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.

140

• 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.

141

• 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:

142

• 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    }}

143

• 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.

144

• 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:

145

• <Button     android:layout_width="wrap_content"     android:layout_height="wrap_content"    android:text="@string/pick_time"     android:onClick="showTimePickerDialog" />

146

• 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");}

147

• 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.

148

• 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.

149

• 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:

150

• 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    }}

151

• 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.

152

• 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:

153

• <Button     android:layout_width="wrap_content"     android:layout_height="wrap_content"    android:text="@string/pick_date"     android:onClick="showDatePickerDialog" />

154

• 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");}

155

• 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.

156

Summary and Mission

• This unit contained items that you can pick from when deciding what you want to do for part 2 of the second assignment.

157

The End

top related