157
Android 9: Input Controls Kirk Scott 1

Android 9: Input Controls

  • Upload
    suzuki

  • View
    63

  • Download
    5

Embed Size (px)

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

Citation preview

Page 1: Android 9:  Input Controls

1

Android 9: Input Controls

Kirk Scott

Page 2: Android 9:  Input Controls

2

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

Page 3: Android 9:  Input Controls

3

Page 4: Android 9:  Input Controls

4

Page 5: Android 9:  Input Controls

5

Page 6: Android 9:  Input Controls

6

Page 7: Android 9:  Input Controls

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

Page 8: Android 9:  Input Controls

8

9.1 Introduction

Page 9: Android 9:  Input Controls

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

Page 10: Android 9:  Input Controls

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

Page 11: Android 9:  Input Controls

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

Page 12: Android 9:  Input Controls

12

9.2 Input Controls

Page 13: Android 9:  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.

Page 14: Android 9:  Input Controls

14

Page 15: Android 9:  Input Controls

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

Page 16: Android 9:  Input Controls

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>

Page 17: Android 9:  Input Controls

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

Page 18: Android 9:  Input Controls

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

Page 19: Android 9:  Input Controls

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.

Page 20: Android 9:  Input Controls

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

Page 21: Android 9:  Input Controls

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

Page 22: Android 9:  Input Controls

22

9.3 Buttons

Page 23: Android 9:  Input Controls

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:

Page 24: Android 9:  Input Controls

24

• With text, using the Button class:

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

Page 25: Android 9:  Input Controls

25

• With an icon, using the ImageButton class:

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

Page 26: Android 9:  Input Controls

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

Page 27: Android 9:  Input Controls

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.

Page 28: Android 9:  Input Controls

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:

Page 29: Android 9:  Input Controls

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

Page 30: Android 9:  Input Controls

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}

Page 31: Android 9:  Input Controls

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)

Page 32: Android 9:  Input Controls

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

Page 33: Android 9:  Input Controls

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

Page 34: Android 9:  Input Controls

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

Page 35: Android 9:  Input Controls

35

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

Page 36: Android 9:  Input Controls

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.

Page 37: Android 9:  Input Controls

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

Page 38: Android 9:  Input Controls

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

Page 39: Android 9:  Input Controls

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

Page 40: Android 9:  Input Controls

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.

Page 41: Android 9:  Input Controls

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.

Page 42: Android 9:  Input Controls

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:

Page 43: Android 9:  Input Controls

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

Page 44: Android 9:  Input Controls

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.

Page 45: Android 9:  Input Controls

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.

Page 46: Android 9:  Input Controls

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.

Page 47: Android 9:  Input Controls

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.

Page 48: Android 9:  Input Controls

48

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

• Insert the following XML:

Page 49: Android 9:  Input Controls

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

Page 50: Android 9:  Input Controls

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

Page 51: Android 9:  Input Controls

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.

Page 52: Android 9:  Input Controls

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:

Page 53: Android 9:  Input Controls

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

Page 54: Android 9:  Input Controls

54

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

Page 55: Android 9:  Input Controls

55

9.4 Text Fields

Page 56: Android 9:  Input Controls

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.

Page 57: Android 9:  Input Controls

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

Page 58: Android 9:  Input Controls

58

Page 59: Android 9:  Input Controls

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.

Page 60: Android 9:  Input Controls

60

• Figure 1. The default text input type.

Page 61: Android 9:  Input Controls

61

• Figure 2. The textEmailAddress input type.

Page 62: Android 9:  Input Controls

62

• Figure 3. The phone input type.

Page 63: Android 9:  Input Controls

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.

Page 64: Android 9:  Input Controls

64

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

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

Page 65: Android 9:  Input Controls

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.

Page 66: Android 9:  Input Controls

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.

Page 67: Android 9:  Input Controls

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

Page 68: Android 9:  Input Controls

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

Page 69: Android 9:  Input Controls

69

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

Page 70: Android 9:  Input Controls

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

Page 71: Android 9:  Input Controls

71

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

Page 72: Android 9:  Input Controls

72

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

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

Page 73: Android 9:  Input Controls

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

Page 74: Android 9:  Input Controls

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.

Page 75: Android 9:  Input Controls

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.

Page 76: Android 9:  Input Controls

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:

Page 77: Android 9:  Input Controls

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

Page 78: Android 9:  Input Controls

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:

Page 79: Android 9:  Input Controls

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

Page 80: Android 9:  Input Controls

80

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

Page 81: Android 9:  Input Controls

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.

Page 82: Android 9:  Input Controls

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.

Page 83: Android 9:  Input Controls

83

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

Page 84: Android 9:  Input Controls

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.

Page 85: Android 9:  Input Controls

85

• Figure 7. Example of AutoCompleteTextView with text suggestions.

Page 86: Android 9:  Input Controls

86

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

Page 87: Android 9:  Input Controls

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

Page 88: Android 9:  Input Controls

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>

Page 89: Android 9:  Input Controls

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

Page 90: Android 9:  Input Controls

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

Page 91: Android 9:  Input Controls

91

9.5 Checkboxes

Page 92: Android 9:  Input Controls

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.

Page 93: Android 9:  Input Controls

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.

Page 94: Android 9:  Input Controls

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.

Page 95: Android 9:  Input Controls

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:

Page 96: Android 9:  Input Controls

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>

Page 97: Android 9:  Input Controls

97

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

Page 98: Android 9:  Input Controls

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

Page 99: Android 9:  Input Controls

99

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

Page 100: Android 9:  Input Controls

100

9.6 Radio Buttons

Page 101: Android 9:  Input Controls

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.

Page 102: Android 9:  Input Controls

102

Page 103: Android 9:  Input Controls

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.

Page 104: Android 9:  Input Controls

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.

Page 105: Android 9:  Input Controls

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:

Page 106: Android 9:  Input Controls

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>

Page 107: Android 9:  Input Controls

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:

Page 108: Android 9:  Input Controls

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

Page 109: Android 9:  Input Controls

109

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

Page 110: Android 9:  Input Controls

110

9.7 Toggle Buttons

Page 111: Android 9:  Input Controls

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.

Page 112: Android 9:  Input Controls

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.

Page 113: Android 9:  Input Controls

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.

Page 114: Android 9:  Input Controls

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:

Page 115: Android 9:  Input Controls

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

Page 116: Android 9:  Input Controls

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

Page 117: Android 9:  Input Controls

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.

Page 118: Android 9:  Input Controls

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.

Page 120: Android 9:  Input Controls

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

Page 121: Android 9:  Input Controls

121

9.8 Spinners

Page 122: Android 9:  Input Controls

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.

Page 123: Android 9:  Input Controls

123

Page 124: Android 9:  Input Controls

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.

Page 125: Android 9:  Input Controls

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:

Page 126: Android 9:  Input Controls

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>

Page 127: Android 9:  Input Controls

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:

Page 128: Android 9:  Input Controls

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

Page 129: Android 9:  Input Controls

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.

Page 131: Android 9:  Input Controls

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:

Page 132: Android 9:  Input Controls

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

Page 134: Android 9:  Input Controls

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.

Page 135: Android 9:  Input Controls

135

9.9 Pickers

Page 136: Android 9:  Input Controls

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.

Page 137: Android 9:  Input Controls

137

Page 138: Android 9:  Input Controls

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.

Page 139: Android 9:  Input Controls

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.

Page 140: Android 9:  Input Controls

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.

Page 141: Android 9:  Input Controls

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:

Page 142: Android 9:  Input Controls

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

Page 143: Android 9:  Input Controls

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.

Page 144: Android 9:  Input Controls

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:

Page 145: Android 9:  Input Controls

145

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

Page 146: Android 9:  Input Controls

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

Page 147: Android 9:  Input Controls

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.

Page 148: Android 9:  Input Controls

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.

Page 149: Android 9:  Input Controls

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:

Page 150: Android 9:  Input Controls

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

Page 151: Android 9:  Input Controls

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.

Page 152: Android 9:  Input Controls

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:

Page 153: Android 9:  Input Controls

153

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

Page 154: Android 9:  Input Controls

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

Page 155: Android 9:  Input Controls

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.

Page 156: Android 9:  Input Controls

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.

Page 157: Android 9:  Input Controls

157

The End