Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Android 10: Input Controls Kirk Scott 1

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

3 3

4 4

5 5

6 6

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

8 10.1 Introduction 8

9 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

10 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

11 10.2 Input Controls 11

12 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 13

14 Adding an input control to your UI is as simple as adding an XML element to your XML layout.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

15 15

16 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

17 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

18 Note: Android provides several more controls than are listed here. Browse the android.widget package to discover more.android.widget If your app requires a specific kind of input control, you can build your own custom components.custom components 18

19 Control TypeDescriptionRelated 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 EditTextEditText, AutoCompleteTextView 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 19

20 Radio button Similar 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. DatePickerDatePicker, TimePickerTimePicker 20 Control TypeDescriptionRelated Classes

21 10.3 Buttons 21

22 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

23 With text, using the Button class:Button 23

24 With an icon, using the ImageButton class:ImageButton 24

25 With text and an icon, using the Button class with the android:drawableLeft attribute:Buttonandroid:drawableLeft 25

26 Responding to Click Events When the user clicks a button, the Button object receives an on-click event.Button To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout.android:onClick 26

27 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.Activity For example, here's a layout with a button using android:onClick:android:onClick 27

28 28

29 Within the Activity that hosts this layout, the following method handles the click event:Activity /** Called when the user touches the button */ public void sendMessage(View view) { // Do something in response to button click } 29

30 The method you declare in the android:onClick attribute must have a signature exactly as shown above. android:onClick Specifically, the method must: Be public Return void Define a View as its only parameter (this will be the View that was clicked)View 30

31 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. ButtonFragment [Notice the two conditions: Either you’re creating the button at run time, Or you’re coding with fragments.] 31

32 To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener). View.OnClickListener setOnClickListener(View.OnClickListener) For example: [Wait. See the following overheads.] 32

33 [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

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

35 [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

36 [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

37 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

38 [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

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

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 in your manifest's element. Also read the blog post, Holo Everywhere for information about using the Holo theme while supporting older devices.Holo Everywhere 40

41 To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource.android:background 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. Styles and Themes 41

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. borderlessButtonStyle For example: 42

43 43

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

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

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.Nine- patch 46

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.10.png button_pressed.10.png button_focused.10.png. 47

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

49 [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

50 This defines a single drawable resource, which will change its image based on the current state of the button. – The first defines the bitmap to use when the button is pressed (activated). – The second defines the bitmap to use when the button is focused (when the button is highlighted using the trackball or directional pad). – The third defines the bitmap to use when the button is in the default state (it's neither pressed nor focused). 50

51 Note: The order of the elements is important. When this drawable is referenced, the elements are traversed in-order to determine which one is appropriate for the current button state. 51

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.Button 4. Then simply apply the drawable XML file as the button background: 52

53 53

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

55 10.4 Text Fields 55

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

57 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. EditText You should usually do so in your XML layout with an element. 57

58 58

59 Specifying the Keyboard Type Text fields can have different input types, such as number, date, password, or 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

60 Figure 1. The default text input type. 60

61 Figure 2. The text Address input type. 61

62 Figure 3. The phone input type. 62

63 There are several different input types available for different situations. Here are some of the more common values for android:inputType:android:inputType "text" Normal text keyboard. "text Address" Normal text keyboard with character. 63

64 "textUri" Normal text keyboard with the / character. "number" Basic number keypad. "phone" Phone-style keypad. 64

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.android:inputType The android:inputType attribute allows bitwise combinations so you can specify both a keyboard layout and one or more behaviors at once.android:inputType 65

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

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

68 For example, here's how you can collect a postal address, capitalize each word, and disable text suggestions: 68

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

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

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

72 You can specify the action by setting the android:imeOptions attribute. android:imeOptions For example, here's how you can specify the Send action: 72

73 73

74 If you do not explicitly specify an input action then the system attempts to determine if there are any subsequent android:focusable fields.android:focusable If any focusable fields are found following this one, the system applies the actionNext} action to the current EditText so the user can select Next to move to the next field.EditText 74

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. android:imeOptions 75

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.android:imeOptionsTextView.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.TextView.OnEditorActionListeneronEditorAction()IME_ACTION_SENDIME_ACTION_SEARCH For example, here's how you can listen for when the user clicks the Send button on the keyboard: 76

77 EditText editText = (EditText) findViewById(R.id.search); editText.setOnEditorActionListener(new OnEditorActionListener() public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { sendMessage(); handled = true; } return handled; } }); 77

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:android:imeActionLabel 78

79 79

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

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.android:imeOptions All available flags are listed along with the actions in the android:imeOptions documentation.android:imeOptions 81

82 [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.android:imeOptions 82

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

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.EditTextAutoCompleteTextView To implement auto-complete, you must specify an 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

85 Figure 7. Example of AutoCompleteTextView with text suggestions.AutoCompleteTextView 85

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

87 1. Add the AutoCompleteTextView to your layout. Here's a layout with only the text field:AutoCompleteTextView 87

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): Afghanistan Albania Algeria American Samoa Andorra Angola Anguilla Antarctica... 88

89 3. In your Activity or Fragment, use the following code to specify the adapter that supplies the suggestions:ActivityFragment // 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 adapter = new ArrayAdapter (this, android.R.layout.simple_list_item_1, countries); textView.setAdapter(adapter); 89

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).ArrayAdapter TextView Then assign the adapter to the AutoCompleteTextView by calling setAdapter(). AutoCompleteTextView setAdapter() 90

91 10.5 Checkboxes 91

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

93 To create each checkbox option, create a CheckBox in your layout. CheckBox 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

94 Responding to Click Events When the user selects a checkbox, the CheckBox object receives an on-click event. CheckBox To define the click event handler for a checkbox, add the android:onClick attribute to the element in your XML layout.android:onClick 94

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.Activity For example, here are a couple CheckBox objects in a list:CheckBox 95

96 96

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

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

99 The method you declare in the android:onClick attribute must have a signature exactly as shown above.android:onClick Specifically, the method must: Be public Return void Define a View as its only parameter (this will be the View that was clicked)View Tip: If you need to change the checkbox state yourself (such as when loading a saved CheckBoxPreference), use the setChecked(boolean) or toggle() method.CheckBoxPreferencesetChecked(boolean)toggle() 99

100 10.6 Radio Buttons 100

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.spinner 101

102 102

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

104 Responding to Click Events When the user selects one of the radio buttons, the corresponding RadioButton object receives an on-click event.RadioButton To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout.android:onClick 104

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.Activity For example, here are a couple RadioButton objects:RadioButton 105

106 106

107 Note: The RadioGroup is a subclass of LinearLayout that has a vertical orientation by default.RadioGroup LinearLayout Within the Activity that hosts this layout, the following method handles the click event for both radio buttons:Activity 107

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

109 The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:android:onClick Be public Return void Define a View as its only parameter (this will be the View that was clicked)View 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. CheckBoxPreference setChecked(boolean)toggle() 109

110 10.7 Toggle Buttons 110

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.ToggleButton 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.Switch 111

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.ToggleButtonSwitchCompoundButton 112

113 Responding to Click Events When the user selects a ToggleButton and Switch, the object receives an on-click event.ToggleButton Switch To define the click event handler, add the android:onClick attribute to the or element in your XML layout. android:onClick 113

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.Activity For example, here's a ToggleButton with the android:onClick attribute:ToggleButton android:onClick 114

115 115

116 Within the Activity that hosts this layout, the following method handles the click event:Activity public void onToggleClicked(View view) { // Is the toggle on? boolean on = ((ToggleButton) view).isChecked(); if (on) { // Enable vibrate } else { // Disable vibrate } } 116

117 The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:android:onClick Be public Return void Define a View as its only parameter (this will be the View that was clicked)View Tip: If you need to change the state yourself, use the setChecked(boolean) or toggle() method to change the state.setChecked(boolean)toggle() 117

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. ToggleButtonSwitch Fragment 118

119 To declare the event handler programmatically, create an CompoundButton.OnCheckedChangeListener object and assign it to the button by calling setOnCheckedChangeListener(CompoundButt on.OnCheckedChangeListener). CompoundButton.OnCheckedChangeListener setOnCheckedChangeListener(CompoundButt on.OnCheckedChangeListener) For example: 119

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

121 10.8 Spinners 121

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

123 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 element. For example:Spinner To populate the spinner with a list of choices, you then need to specify a SpinnerAdapter in your Activity or Fragment source code.SpinnerAdapterActivity Fragment 124

125 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. SpinnerAdapterArrayAdapter CursorAdapter 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:string resource file 125

126 Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune 126

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:Activity FragmentArrayAdapter 127

128 Spinner spinner = (Spinner) findViewById(R.id.spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter 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

129 The createFromResource() method allows you to create an ArrayAdapter from the string array.createFromResource()ArrayAdapter 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.simple_spinner_item 129

130 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). setDropDownViewResource(int)simple_spinner_dropdown_item Call setAdapter() to apply the adapter to your Spinner.setAdapter() Spinner 130

131 Responding to User Selections When the user selects an item from the drop- down, the Spinner object receives an on-item- selected event.Spinner To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. AdapterView.OnItemSelectedListeneronItemSelected() For example, here's an implementation of the interface in an Activity:Activity 131

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

133 The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods.AdapterView.OnItemSelectedListeneronItemSelected() onNothingSelected() Then you need to specify the interface implementation by calling setOnItemSelectedListener(): setOnItemSelectedListener() Spinner spinner = (Spinner) findViewById(R.id.spinner); spinner.setOnItemSelectedListener(this); 133

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. AdapterView.OnItemSelectedListenerActivityFragment 134

135 10.10 Pickers 135

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

137 137

138 We recommend that you use DialogFragment to host each time or date picker.DialogFragment 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.DialogFragment 138

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.DialogFragment support library Note: The code samples below show how to create dialogs for a time picker and date picker using the support library APIs for DialogFragment. support libraryDialogFragment If your app's minSdkVersion is 11 or higher, you can instead use the platform version of DialogFragment.minSdkVersionDialogFragment 139

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.TimePickerDialog DialogFragment TimePickerDialog onCreateDialog() 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.Setting Up a Project to Use a Library 140

141 Extending DialogFragment for a time picker To define a DialogFragment for a TimePickerDialog, you must:DialogFragment TimePickerDialog Define the onCreateDialog() method to return an instance of TimePickerDialogonCreateDialog()TimePickerDialog Implement the TimePickerDialog.OnTimeSetListener interface to receive a callback when the user sets the time. TimePickerDialog.OnTimeSetListener Here's an example: 141

142 public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener 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 } } 142

143 See the TimePickerDialog class for information about the constructor arguments.TimePickerDialog Now all you need is an event that adds an instance of this fragment to your activity. 143

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().DialogFragment show() For example, here's a button that, when clicked, calls a method to show the dialog: 144

145 145

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

147 This method calls show() on a new instance of the DialogFragment defined above.show() DialogFragment The show() method requires an instance of FragmentManager and a unique tag name for the fragment.show() FragmentManager Caution: If your app supports versions of Android lower than 3.0, be sure that you call getSupportFragmentManager() to acquire an instance of FragmentManager. getSupportFragmentManager()FragmentManager Also make sure that your activity that displays the time picker extends FragmentActivity instead of the standard Activity class.FragmentActivityActivity 147

148 Creating a Date Picker Creating a DatePickerDialog is just like creating a TimePickerDialog.DatePickerDialog 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.DatePickerDialogDialogFragment DatePickerDialogonCreateDialog() 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.Setting Up a Project to Use a Library 148

149 Extending DialogFragment for a date picker To define a DialogFragment for a DatePickerDialog, you must:DialogFragment DatePickerDialog Define the onCreateDialog() method to return an instance of DatePickerDialogonCreateDialog()DatePickerDialog Implement the DatePickerDialog.OnDateSetListener interface to receive a callback when the user sets the date. DatePickerDialog.OnDateSetListener Here's an example: 149

150 public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener 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

151 See the DatePickerDialog class for information about the constructor arguments.DatePickerDialog Now all you need is an event that adds an instance of this fragment to your activity. 151

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().DialogFragment show() For example, here's a button that, when clicked, calls a method to show the dialog: 152

153 153

154 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

155 This method calls show() on a new instance of the DialogFragment defined above.show() DialogFragment The show() method requires an instance of FragmentManager and a unique tag name for the fragment.show() FragmentManager 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. getSupportFragmentManager()FragmentManagerFragmentActivityActivity 155

156 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

157 The End 157


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

Similar presentations


Ads by Google