Chapter 4 - User Interaction
Chapter 4 - User Interaction
Chapter 4 - User Interaction
CHAPTER 4
Learning Outcomes
• Use buttons and clickable images for triggering actions
initiated by the user.
• Use input controls such as switches, spinners and more.
• Understand types of menus, dialogs and pickers.
• Understand different ways to enable users to navigate
through your app.
User interaction
3
Users expect to interact with apps
4
User interaction design
5
Buttons
6
Button
7
Button image assets
1. Right-click app/res/drawable
2. Choose New > Image Asset
3. Choose Action Bar and Tab Items from
drop down menu
4. Click the Clipart: image
(the Android logo) Experiment:
2. Choose New > Vector Asset
8
Responding to button taps
9
Setting listener with onClick callback
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
10
Clickable
images
11
ImageView
12
Responding to ImageView taps
<ImageView
android:layout_width="wrap_content" android:onClick
android:layout_height="wrap_content"
android:src="@drawable/donut_circle"
android:onClick="orderDonut"/>
13
Floating action
button
14
Floating Action Buttons (FAB)
For example:
Add Contact button in Contacts app
15
Using FABs
● Start with Basic Activity template
● Layout:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/ic_fab_chat_button_white"
.../>
16
FAB size
● 56 x 56 dp by default
● Set mini size (30 x 40 dp) with app:fabSize attribute:
○ app:fabSize="mini"
● Set to 56 x 56 dp (default):
○ app:fabSize="normal"
17
Common
Gestures
18
Touch Gestures
19
Detect gestures
20
Detecting all types of gestures
21
Overview of
input Controls
22
Accepting user input
23
Examples of input controls
1. EditText
2. SeekBar
3. CheckBox
4. RadioButton
5. Switch
6. Spinner
24
How input controls work
1. Use EditText for entering text using keyboard
2. Use SeekBar for sliding left or right to a setting
3. Combine CheckBox elements for choosing more than one
option
4. Combine RadioButton elements into RadioGroup — user
makes only one choice
5. Use Switch for tapping on or off
6. Use Spinner for choosing a single item from a list
25
View is base class for input controls
● The View class is the basic building block for all UI components,
including input controls
● View is the base class for classes that provide interactive UI
components
● View provides basic interaction through android:onClick
26
View focus
27
Focus
28
Clickable versus focusable
29
Which View gets focus next?
30
Guiding users
31
Guiding focus
33
Find the view with focus
● Activity.getCurrentFocus()
● ViewGroup.getFocusedChild()
34
Freeform text
and numbers
35
EditText for multiple lines of text
● EditText default
● Alphanumeric keyboard
● Suggestions appear
● Tapping Return (Enter) key starts
new line
Return key
36
Customize with inputType
37
EditText for message
● android:inputType
="textShortMessage"
● Single line of text
● Tapping Emoticons key changes
keyboard to emoticons
Emoticons
38
EditText for single line
● Both work:
○ android:inputType
="textLongMessage"
○ android:inputType
="textPersonName"
● Single line of text
● Tapping Done key advances focus
to next View
Done key
39
EditText for phone number entry
● android:inputType ="phone"
● Numeric keypad (numbers only)
● Tapping Done key advances focus
to next View
Done key
40
Getting text
41
Input types
Common input types
● textCapCharacters: Set to all capital letters
● textCapSentences: Start each sentence with a capital letter
● textPassword: Conceal an entered password
● number: Restrict text entry to numbers
● textEmailAddress: Show keyboard with @ conveniently located
● phone: Show a numeric phone keypad
● datetime: Show a numeric keypad with a slash and colon for
entering the date and time
42
Providing
choices
43
UI elements for providing choices
● Spinner
44
CheckBox
45
RadioButton
● Put RadioButton elements in a RadioGroup in a
vertical list (horizontally if labels are short)
● User can select only one of the choices
● Checking one unchecks all others in group
● Each RadioButton can have onClick
handler
● Commonly used with a Submit button
for the RadioGroup
46
Toggle buttons and switches
● User can switch between on and off
● Use android:onClick for click handler
Toggle buttons
Switches
47
Menus and
pickers
48
Types of Menus
1. App bar with options
menu
2. Context menu
3. Contextual action bar
4. Popup menu
49
Dialogs and pickers
1. Alert dialog
2. Date picker
3. Time picker
1 2 3
50
App Bar with
Options Menu
51
What is the App Bar?
Bar at top of each screen—same for all devices (usually)
1. Nav icon to open navigation drawer
2. Title of current Activity
3. Icons for options menu items
4. Action overflow button for
the rest of the options menu
52
What is the options menu?
● Action icons in the app bar
for important items (1)
● Tap the three dots, the
"action overflow button" to
see the options menu (2)
53
Adding Options
Menu
54
Steps to implement options menu
1. XML menu resource (menu_main.xml)
2. onCreateOptionsMenu() to inflate the menu
3. onClick attribute or onOptionsItemSelected()
4. Method to handle item click
55
Create menu resource
1. Create menu resource directory
2. Create XML menu resource (menu_main.xml)
3. Add entry for each menu item (Settings and Favorites):
<item android:id="@+id/option_settings"
android:title="Settings" />
<item android:id="@+id/option_favorites"
android:title="Favorites" />
56
Inflate options menu
Override onCreateOptionsMenu() in Activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
57
Add icons for menu items
1. Right-click drawable
2. Choose New > Image Asset
3. Choose Action Bar and Tab Items
4. Edit the icon name
5. Click clipart image, and click icon
6. Click Next, then Finish
58
Add menu item attributes
<item
android:id="@+id/action_favorites"
android:icon="@drawable/ic_favorite"
android:orderInCategory="30"
android:title="@string/action_favorites"
app:showAsAction="ifRoom" />
59
Override onOptionsItemSelected()
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
showSettings();
return true;
case R.id.action_favorites:
showFavorites();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
60
Contextual
Menus
61
What are contextual menus?
62
Types of contextual menus
● Floating context menu—long-press on a View
○ User can modify View or use it in some fashion
○ User performs action on one View at a time
● Contextual action mode—temporary action bar in place
of or underneath app bar
○ Action items affect the selected View element(s)
○ User can perform action on multiple View elements at
once
63
Floating
Context Menu
64
Steps
1. Create XML menu resource file and assign appearance and position
attributes
2. Register View using registerForContextMenu()
3. Implement onCreateContextMenu() in Activity to inflate menu
4. Implement onContextItemSelected() to handle menu item clicks
5. Create method to perform action for each context menu item
65
Create menu resource
1. Create XML menu resource (menu_context.xml)
<item
android:id="@+id/context_edit"
android:title="Edit"
android:orderInCategory="10"/>
<item
android:id="@+id/context_share"
android:title="Share"
android:orderInCategory="20"/>
66
Register a view to a context menu
67
Implement onCreateContextMenu()
onCreateContextMenu() method
3. Specify which context menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
}
68
Implement onContextItemSelected()
onCreateContextMenu() method
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_edit:
editNote();
return true;
case R.id.context_share:
shareNote();
return true;
default:
return super.onContextItemSelected(item);
}
}
69
Contextual
Action Bar
70
What is Action Mode?
● UI mode that lets you replace parts of normal UI interactions
temporarily
● For example: Selecting a section of text or long-pressing an
item could trigger action mode
71
Action mode has a lifecycle
● Start it with startActionMode(), for example, in the listener
72
What is a contextual action bar?
Long-press on View shows contextual action bar
1. Contextual action bar with actions
○ Edit, Share, and Delete
○ Done (left arrow icon) on left side
○ Action bar is available until user taps Done
2. View on which long press triggers
contextual action bar
73
Steps for contextual action bar
1. Create XML menu resource file and
assign icons for items
2. setOnLongClickListener() on View
that triggers contextual action
bar and call startActionMode() to
handle click
3. Implement ActionMode.Callback interface to handle ActionMode
lifecycle; include action for menu item click in onActionItemClicked()
callback
4. Create method to perform action for each context menu item
74
Use setOnLongClickListener
private ActionMode mActionMode;
In onCreate():
View view = findViewById(article);
view.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mActionMode != null) return false;
mActionMode =
MainActivity.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
75
Implement mActionModeCallback
76
Implement onCreateActionMode
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
return true;
}
77
Implement onPrepareActionMode
● Called each time action mode is shown
● Always called after onCreateActionMode, but may be called multiple
times if action mode is invalidated
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done.
}
78
Implement onActionItemClicked
● Called when users selects an action
● Handle clicks in this method
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_share:
// Perform action for the Share menu item.
mode.finish(); // Action picked, so close the action bar.
return true;
default:
return false;
}
}
79
Implement onDestroyActionMode
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
80
Popup Menu
81
What is a popup menu?
● Vertical list of items anchored to a view
● Typically anchored to a visible icon
● Actions should not directly affect view content
○ Options menu overflow icon that opens options menu
○ In email app, Reply All and Forward relate to email
message but don’t affect or act on message
82
Steps
1. Create XML menu resource file and assign appearance and position
attributes
2. Add ImageButton for the popup menu icon in the XML activity layout file
3. Assign onClickListener to ImageButton
4. Override onClick() to inflate the popup and register it with
onMenuItemClickListener()
5. Implement onMenuItemClick()
6. Create a method to perform an action for each popup menu item
83
Add ImageButton
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_popup"
android:src="@drawable/@drawable/ic_action_popup"/>
84
Assign onClickListener to button
private ImageButton mButton =
(ImageButton) findViewById(R.id.button_popup);
In onCreate():
mButton.setOnClickListener(new View.OnClickListener() {
// define onClick
});
85
Implement onClick
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, mButton);
popup.getMenuInflater().inflate(
R.menu.menu_popup, popup.getMenu());
popup.setOnMenuItemClickListener(
new PopupMenu.OnMenuItemClickListener() {
// implement click listener.
});
popup.show();
}
86
Implement onMenuItemClick
87
Dialogs
88
Dialogs
● Dialog appears on top, interrupting
flow of Activity
● Requires user action to dismiss
89
AlertDialog
90
Build the AlertDialog
AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Connect to Provider");
alertDialog.setMessage(R.string.alert_message);
// ... Code to set buttons goes here.
91
Set the button actions
● alertDialog.setPositiveButton()
● alertDialog.setNeutralButton()
● alertDialog.setNegativeButton()
92
alertDialog code example
alertDialog.setPositiveButton(
"OK", newDialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User clicked OK button.
}
});
93
Pickers
94
Pickers
● DatePickerDialog
● TimePickerDialog
95
Pickers use fragments
96
Introduction to fragments
97
Creating a date picker dialog
1. Add a blank Fragment that extends DialogFragment and
implements DatePickerDialog.OnDateSetListener
2. In onCreateDialog() initialize the date and return the dialog
3. In onDateSet() handle the date
4. In Activity show the picker and add method to use date
98
Creating a time picker dialog
1. Add a blank Fragment that extends DialogFragment and
implements TimePickerDialog.OnTimeSetListener
2. In onCreateDialog() initialize the time and return the dialog
3. In onTimeSet() handle the time
4. In Activity, show the picker and add method to use time
99
User Navigation
100
Two forms of navigation
101
Back Navigation
102
Navigation through history of screens
1. Historys starts from Launcher
103
Changing Back button behavior
● Android system manages the back stack and Back button
● If in doubt, don't change
● Only override, if necessary to satisfy user expectation
104
Overriding onBackPressed()
@Override
public void onBackPressed() {
// Add the Back key handler here.
return;
}
105
Hierarchical
Navigation
106
Hierarchical navigation patterns
● Parent screen—Screen that enables navigation down to child
screens, such as home screen and main Activity
● Collection sibling—Screen enabling navigation to a
collection of child screens, such as a list of headlines
● Section sibling—Screen with content, such as a story
107
Example of a screen hierarchy
1. Parent 1 News App
2. Children: collection siblings
2
3. Children: section siblings Top Stories Tech News Cooking
Headline Headline Headline
Headline Headline Headline
● Use Activity for parent screen Headline Headline Headline
Headline
● Use Activity or Fragment for Headline Headline
children screens
3 Story Story Story
108
Types of hierarchical navigation
● Descendant navigation
○ Down from a parent screen to one of its children
○ From a list of headlines—to a story summary—to a story
● Ancestral navigation
○ Up from a child or sibling screen to its parent
○ From a story summary back to the headlines
● Lateral navigation
○ From one sibling to another sibling
○ Swiping between tabbed views
109
Descendant
Navigation
110
Descendant navigation
Descendant navigation News App
111
Master/detail flow
● Side-by side on tablets ● Multiple screens on phone
112
Controls for descendant navigation
● Navigation drawer
● Buttons, image buttons on main screen
● Other clickable views with text and icons arranged in horizontal
or vertical rows, or as a grid
● List items on collection screens
113
Navigation
Drawer
114
Navigation drawer
Descendant navigation
1. Icon in app bar
2. Header
3. Menu items
115
Layouts for for navigation drawer
Create layouts:
● A navigation drawer as the Activity layout root ViewGroup
● A navigation View for the drawer itself
● An app bar layout that includes room for a navigation icon
button
● A content layout for the Activity that displays the navigation
drawer
● A layout for the navigation drawer header
116
Navigation drawer Activity layout
1. DrawerLayout is root view
2. CoordinatorLayout contains
app bar layout with a Toolbar
3. App content screen layout
4. NavigationView with layouts for 3
117
Steps to implement navigation drawer
118
Other descendant navigation patterns
119
Ancestral
Navigation
120
Ancestral navigation (Up button)
● Enable user to go up from a section
or child screen to the parent
121
Declare parent of child Activity—
AndroidManifest
<activity android:name=".OrderActivity"
android:label="@string/title_activity_order"
android:parentActivityName="com.example.android.
optionsmenuorderactivity.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
122
Lateral
Navigation
123
Tabs and swipes
Lateral navigation News App
● Between siblings
Top Stories Tech News Cooking
● From a list of stories to a Headline Headline Headline
Headline Headline Headline
list in a different tab Headline Headline Headline
Headline Headline Headline
● From story to story under
the same tab
Story Story Story
124
Benefits of using tabs and swipes
● A single, initially-selected tab—users
have access to content without further
navigation
● Navigate between related screens
without visiting parent
125
Best practices with tabs
126
Steps for implementing tabs
1. Define the tab layout using TabLayout
2. Implement a Fragment and its layout for each tab
3. Implement a PagerAdapter from FragmentPagerAdapter or
FragmentStatePagerAdapter
4. Create an instance of the tab layout
5. Use PagerAdapter to manage screens (each screen is a Fragment)
6. Set a listener to determine which tab is tapped
127
Add tab layout below Toolbar
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/ >
128
Add view pager below TabLayout
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/tab_layout" />
129
Create a tab layout in onCreate()
130
Add the view pager in onCreate()
131
Add the listener in onCreate()
viewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());}
@Override
public void onTabUnselected(TabLayout.Tab tab) {}
@Override
public void onTabReselected(TabLayout.Tab tab) {} });
132
RecyclerView
133
What is a RecyclerView?
134
RecyclerView
Components
135
Components
Overview
● Data
● RecyclerView scrolling list for list items—RecyclerView
● Layout for one item of data—XML file
● Layout manager handles the organization of UI components in a View—
Recyclerview.LayoutManager
● Adapter connects data to the RecyclerView—RecyclerView.Adapter
● ViewHolder has view information for displaying one item—
RecyclerView.ViewHolder
136
Components
How components fit together overview
137
LayoutisManager
What a layout manager?
● Each ViewGroup has a layout manager
● Use to position View items inside a RecyclerView
● Reuses View items that are no longer visible to the user
● Built-in layout managers
○ LinearLayoutManager
○ GridLayoutManager
○ StaggeredGridLayoutManager
● Extend RecyclerView.LayoutManager
138
Adapter
What is an adapter?
139
Adapter
What is a ViewHolder?
● Used by the adapter to prepare one View with data for one
list item
● Layout specified in an XML resource file
● Can have clickable elements
● Is placed by the layout manager
● RecyclerView.ViewHolder
140
Implementing
RecyclerView
141
Implementation
Steps Summary
142
app/build.gradle
Add dependency to app/build.gradle
dependencies {
...
compile 'com.android.support:recyclerview-v7:26.1.0'
...
}
143
Activity
Add RecyclerView
layout to XML Layout
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
144
Item layout
Create layout for 1 list item
<LinearLayout …>
<TextView
android:id="@+id/word"
style="@style/word_title" />
</LinearLayout>
145
Adapter: Create
Implement the adapter
public class WordListAdapter
extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {
146
Adapter:has
Adapter onCreateViewHolder()
3 required methods
● onCreateViewHolder()
● inBindViewHolder()
● getItemCount()
147
Adapter: onCreateViewHolder()
onCreateViewHolder()
@Override
public WordViewHolder onCreateViewHolder(
ViewGroup parent, int viewType) {
// Create view from layout
View mItemView = mInflater.inflate(
R.layout.wordlist_item, parent, false);
return new WordViewHolder(mItemView, this);
}
148
Adapter: onBindViewHolder()
onBindViewHolder()
@Override
public void onBindViewHolder(
WordViewHolder holder, int position) {
// Retrieve the data for that position
String mCurrent = mWordList.get(position);
// Add the data to the view
holder.wordItemView.setText(mCurrent);
}
149
Adapter: getItemCount()
getItemCount()
@Override
public int getItemCount() {
// Return the number of data items to display
return mWordList.size();
}
150
Adapter:
Create the
ViewHolder
view holder
Class
in adapter class
151
ViewHolder:
View holder constructor
Constructor
public WordViewHolder(View itemView, WordListAdapter adapter) {
super(itemView);
// Get the layout
wordItemView = itemView.findViewById(R.id.word);
// Associate with this adapter
this.mAdapter = adapter;
// Add click listener, if desired
itemView.setOnClickListener(this);
}
// Implement onClick() if desired
152
Createthe
Create RecyclerView
RecyclerView in Activity
onCreate()
mRecyclerView = findViewById(R.id.recyclerview);
mAdapter = new WordListAdapter(this, mWordList);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new
LinearLayoutManager(this));
153
Practical: RecyclerView
154
End