Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 4 - User Interaction

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 155

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

● Tapping or clicking, typing, using gestures, and talking


● Buttons perform actions
● Other UI elements enable data input and navigation

4
User interaction design

Important to be obvious, easy, and consistent:


● Think about how users will use your app
● Minimize steps
● Use UI elements that are easy to access, understand, use
● Follow Android best practices
● Meet user's expectations

5
Buttons

6
Button

● View that responds to tapping (clicking) or pressing


● Usually text or visuals indicate what will happen when tapped
● State: normal, focused, disabled, pressed, on/off

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

● In your code: Use OnClickListener event listener.


● In XML: use android:onClick attribute in the XML layout:
<Button
android:id="@+id/button_send"
android:onClick
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />

9
Setting listener with onClick callback

Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});

10
Clickable
images

11
ImageView

● ImageView with android:onClick attribute


● Image for ImageView in app>src>main>res>drawable folder in
project

12
Responding to ImageView taps

● In your code: Use OnClickListener event listener.


● In XML: use android:onClick attribute in the XML layout:

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

● Raised, circular, floats above layout


● Primary or "promoted" action for a screen
● One per screen

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

Touch gestures include:


● long touch
● double-tap Don’t depend on touch
● fling gestures for app's basic
● drag
behavior!
● scroll
● pinch

19
Detect gestures

Classes and methods are available to help you handle gestures.


● GestureDetectorCompat class for common gestures
● MotionEvent class for motion events

20
Detecting all types of gestures

1. Gather data about touch events.


2. Interpret the data to see if it meets the criteria for any of
the gestures your app supports.
Read more about how to handle gestures in the
Android developer documentation

21
Overview of
input Controls

22
Accepting user input

● Freeform text and numbers: EditText (using keyboard)


● Providing choices: CheckBox, RadioButton, Spinner
● Switching on/off: Toggle, Switch
● Choosing value in range of values: SeekBar

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

● The View that receives user input has "Focus"


● Only one View can have focus
● Focus makes it unambiguous which View gets the input
● Focus is assigned by
○ User tapping a View
○ App guiding the user from one text input control to the
next using the Return, Tab, or arrow keys
○ Calling requestFocus() on any View that is focusable

28
Clickable versus focusable

Clickable—View can respond to being clicked or tapped


Focusable—View can gain focus to accept input
Input controls such as keyboards send input to the view that has
focus

29
Which View gets focus next?

● Topmost view under the touch


● After user submits input, focus moves to nearest neighbor—
priority is left to right, top to bottom
● Focus can change when user interacts with a directional
control

30
Guiding users

● Visually indicate which view has focus so users knows where


their input goes
● Visually indicate which views can have focus helps users
navigate through flow
● Predictable and logical—no surprises!

31
Guiding focus

● Arrange input controls in a layout from left to right


and top to bottom in the order you want focus
assigned
● Place input controls inside a view group in your
layout
● Specify ordering in XML
android:id="@+id/top"
android:focusable="true"
android:nextFocusDown="@+id/bottom"
32
Set focus explicitly

Use methods of the View class to set focus

● setFocusable() sets whether a view can have focus


● requestFocus() gives focus to a specific view
● setOnFocusChangeListener() sets listener for when view gains
or loses focus
● onFocusChanged() called when focus on a view changes

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

● Set in Attributes pane of layout editor

● XML code for EditText:


<EditText
android:id="@+id/name_field"
android:inputType =
"textPersonName"
...

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

● Get the EditText object for the EditText view


EditText simpleEditText =
findViewById(R.id.edit_simple);

● Retrieve the CharSequence and convert it to a string


String strValue =
simpleEditText.getText().toString();

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

● CheckBox and RadioButton

● ToggleButton and Switch

● Spinner

44
CheckBox

● User can select any number of choices


● Checking one box does not uncheck another
● Users expect checkboxes in a vertical list
● Commonly used with a Submit button
● Every CheckBox is a View and can have
an onClick handler

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)

● Appears in the right corner of the app bar (3)


● For navigating to other activities and editing app settings

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?

● Allows users to perform action on selected View


● Can be deployed on any View
● Most often used for items in RecyclerView, GridView, or other
View collection

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

In onCreate() of the Activity:


2. Register View.OnCreateContextMenuListener to View:

TextView article_text = findViewById(R.id.article);


registerForContextMenu(article_text);

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

● ActionMode.Callback interface provides lifecycle methods you override:


○ onCreateActionMode(ActionMode, Menu) once on initial creation
○ onPrepareActionMode(ActionMode, Menu) after creation and any time
ActionMode is invalidated
○ onActionItemClicked(ActionMode, MenuItem) any time contextual
action button is clicked
○ onDestroyActionMode(ActionMode) when action mode is closed

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

public ActionMode.Callback mActionModeCallback =


new ActionMode.Callback() {
// Implement action mode callbacks here.
};

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

● Called when user exits the action mode

@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

public boolean onMenuItemClick(MenuItem item) {


switch (item.getItemId()) {
case R.id.option_forward:
// Implement code for Forward button.
return true;
default:
return false;
}
}

87
Dialogs

88
Dialogs
● Dialog appears on top, interrupting
flow of Activity
● Requires user action to dismiss

TimePickerDialog DatePickerDialog AlertDialog

89
AlertDialog

AlertDialog can show:


1. Title (optional)
2. Content area
3. Action buttons

90
Build the AlertDialog

Use AlertDialog.Builder to build alert dialog and set attributes:

public void onClickShowAlert(View view) {


AlertDialog.Builder alertDialog = new

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

Same pattern for setNegativeButton() and setNeutralButton()

93
Pickers

94
Pickers

● DatePickerDialog
● TimePickerDialog

95
Pickers use fragments

● Use DialogFragment to show a picker


● DialogFragment is a window that floats
on top of Activity window

96
Introduction to fragments

● A Fragment is like a mini-Activity within an Activity


○ Manages its own own lifecycle
○ Receives its own input events
● Can be added or removed while parent Activity is running
● Multiple fragments can be combined in a single Activity
● Can be reused in more than one Activity

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

Back (temporal) navigation


● Provided by the device's Back button
● Controlled by the Android system back stack

Ancestral (Up) navigation


● Up button provided in app bar
● Controlled by defining parent Activity for child
Activity in the AndroidManifest.xml

101
Back Navigation

102
Navigation through history of screens
1. Historys starts from Launcher

2. User clicks the Back button to


navigate to previous screens in
reverse order

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

For example: In an embedded browser, trigger browser's default


back behavior when user presses device Back button

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

● Down from a parent screen


Top Stories Tech News Cooking
to one of its children Headline Headline Headline
Headline Headline Headline
● From the main screen to a Headline Headline Headline
list of headlines to a story Headline Headline Headline

Story Story Story

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

header and selectable items


4

117
Steps to implement navigation drawer

1. Populate navigation drawer menu with item titles and icons


2. Set up navigation drawer and item listeners in the Activity
code
3. Handle the navigation menu item selections

118
Other descendant navigation patterns

● Vertical list, such as RecyclerView


● Vertical grid, such as GridView
● Lateral navigation with a carousel
● Multi-level menus, such as the options menu
● Master/detail navigation flow

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

● Lay out horizontally


● Run along top of screen
● Persistent across related screens
● Switching should not be treated as history

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

TabLayout tabLayout = findViewById(R.id.tab_layout);


tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

130
Add the view pager in onCreate()

final ViewPager viewPager = findViewById(R.id.pager);


final PagerAdapter adapter = new PagerAdapter (
getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);

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?

● RecyclerView is scrollable container


for large data sets
● Efficient
○ Uses and reuses limited number
of View elements
○ Updates changing data fast

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?

● Helps incompatible interfaces work together


○ Example: Takes data from database Cursor and prepares
strings to put into a View
● Intermediary between data and View
● Manages creating, updating, adding, deleting View items as
underlying data changes
● RecyclerView.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

1. Add RecyclerView dependency to build.gradle if needed


2. Add RecyclerView to layout
3. Create XML layout for item
4. Extend RecyclerView.Adapter
5. Extend RecyclerView.ViewHolder
6. In Activity onCreate(), create RecyclerView with adapter and
layout manager

142
app/build.gradle
Add dependency to app/build.gradle

Add RecyclerView dependency to build.gradle if needed:

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

public WordListAdapter(Context context,


LinkedList<String> wordList) {
mInflater = LayoutInflater.from(context);
this.mWordList = wordList;
}
}

146
Adapter:has
Adapter onCreateViewHolder()
3 required methods

● onCreateViewHolder()
● inBindViewHolder()
● getItemCount()

Let's take a look!

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

class WordViewHolder extends RecyclerView.ViewHolder { //.. }

If you want to handle mouse clicks:

class WordViewHolder extends RecyclerView.ViewHolder


implements View.OnClickListener { //.. }

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

● This is rather complex with many separate pieces. So, there is


a whole practical where you implement a RecyclerView that
displays a list of clickable words.

● Shows all the steps, one by one with a complete app

154
End

You might also like