Android Tutorial
Android Tutorial
Android Tutorial
Day 1
1
Contents
• Android Introduction
• Android First App
• Layout
• Activity
• Intent
• Button & Images
• Input Control
• Menu & Pickers
2
1.0 Introduction to Android
3
Android Software Developer Kit (SDK)
● Development tools (debugger, monitors, editors)
● Libraries (maps, wearables)
● Virtual devices (emulators)
● Documentation (developers.android.com)
● Sample code
4
Android Studio
● Official Android IDE
● Develop, run, debug,
test, and package apps
● Monitors and
performance tools
● Virtual devices
● Project views
● Visual layout editor
5
Android Platform
Architecture
6
Android stack
7
System and user apps
Example:
Your app can use a system app to deliver a SMS
message.
8
Java API Framework
The entire feature-set of the Android OS is available to you
through APIs written in the Java language.
9
Android runtime
Each app runs in its own process with its own instance of the
Android Runtime.
10
C/C++ libraries
11
Hardware Abstraction Layer (HAL)
12
Linux Kernel
13
Older Android versions
Codename Version Released API Level
14
Newer Android versions
Codename Version Released API Level
15
App Development
16
What is an Android app?
17
Challenges of Android development
18
Creating your
first Android app
19
Start Android Studio
20
Create a project inside Android Studio
21
Name your app
22
Pick activity template
Choose templates for
common activities,
such as maps or
navigation drawers.
24
Project folders
1. manifests—Android Manifest file -
description of app read by the
Android runtime
2. java—Java source code packages
3. res—Resources (XML) - layout,
strings, images, dimensions,
colors...
4. build.gradle—Gradle build files
25
Gradle build system
● Modern build subsystem in Android Studio
● Three build.gradle:
○ project
○ module
○ settings
26
Run your app
1. Run
2. Select virtual
or physical
device
3. OK
27 27
Create a virtual device
Use emulators to test app on different versions of Android and form factors.
28
Configure virtual device
1. Choose hardware
2. Select Android version
3. Finalize
29
Run on a virtual device
30
Run on a physical device
1. Turn on Developer Options:
a. Settings > About phone
b. Tap Build number seven times
2. Turn on USB Debugging
a. Settings > Developer Options > USB Debugging
3. Connect phone to computer with cable
Windows drivers:
● OEM USB Drivers
31
Get feedback as your app runs
1. Emulator
running the
app
2. Run pane
3. Run tab to
open or close
the Run pane
32
Adding logging to your app
● As the app runs, the Logcat pane shows information
● Add logging statements to your app that will show up in the
Logcat pane
● Set filters in Logcat pane to see what's important to you
● Search using tags
33
The Logcat pane
1. Logcat tab to
show Logcat
pane
2. Log level
menu
34
Logging statement
import android.util.Log;
36
Contents
37
Views
38
Everything you see is a view
If you look at your mobile device,
every user interface element that you
see is a View.
Views
39
What is a view?
View subclasses are basic user interface building blocks
● Display text (TextView class), edit text (EditText class)
● Buttons (Button class), menus, other controls
● Scrollable (ScrollView, RecyclerView)
● Show images (ImageView)
● Group views (ConstraintLayout and LinearLayout)
40
Examples of view subclasses
Button CheckBox
EditText RadioButton
Slider Switch
41
View attributes
● Color, dimensions, positioning
● May have focus (e.g., selected to receive user input)
● May be interactive (respond to user clicks)
● May be visible or not
● Relationships to other views
42
Create views and layouts
43
Android Studio layout editor
1. XML layout file
2. Design and Text
tabs
3. Palette pane
4. Component Tree
5. Design and
blueprint panes
6. Attributes tab
44
View defined in XML
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/myBackgroundColor"
android:text="@string/count_initial_value"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/count_text_size"
android:textStyle="bold"
/>
45
View attributes in XML
android:<property_name>="<property_value>"
Example: android:layout_width="match_parent"
android:<property_name>="@<resource_type>/resource_id"
Example: android:text="@string/button_label_next"
android:<property_name>="@+id/view_id"
Example: android:id="@+id/show_count"
46
Create View in Java code
context
In an Activity:
47
What is the context?
● Context is an interface to global information about an
application environment
● Get the context:
Context context = getApplicationContext();
● An Activity is its own context:
TextView myText = new TextView(this);
48
Custom views
● Over 100 (!) different types of views available from the
Android system, all children of the View class
● If necessary, create custom views by subclassing existing
views or the View class
49
ViewGroup and
View hierarchy
50
ViewGroup contains "child" views
● ConstraintLayout: Positions UI elements using
constraint connections to other elements and to the
layout edges
● ScrollView: Contains one element and enables scrolling
● RecyclerView: Contains a list of elements and enables
scrolling by adding and removing elements dynamically
51
ViewGroups for layouts
Layouts
● are specific types of ViewGroups (subclasses of
ViewGroup)
● contain child views
● can be in a row, column, grid, table, absolute
52
Common Layout Classes
53
Common Layout Classes
● ConstraintLayout: Connect views with constraints
● LinearLayout: Horizontal or vertical row
● RelativeLayout: Child views relative to each other
● TableLayout: Rows and columns
● FrameLayout: Shows one child of a stack of children
54
Class hierarchy vs. layout hierarchy
● View class-hierarchy is standard object-oriented class
inheritance
○ For example, Button is-a TextView is-a View is-an Object
○ Superclass-subclass relationship
55
Hierarchy of viewgroups and views
56
View hierarchy and screen layout
57
View hierarchy in the layout editor
58
Layout created in XML
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
... />
<TextView
... />
<Button
... />
</LinearLayout
59
Layout created in Java Activity code
LinearLayout linearL = new LinearLayout(this);
linearL.setOrientation(LinearLayout.VERTICAL);
linearL.addView(myText);
setContentView(linearL);
60
Set width and height in Java code
Set the width and height of a view:
LinearLayout.LayoutParams layoutParams =
new Linear.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_CONTENT);
myView.setLayoutParams(layoutParams);
61
The layout
editor and
Constraint
Layout
62
The layout editor with ConstraintLayout
63
What is ConstraintLayout?
64
Layout editor main toolbar
● Enable Autoconnect in
toolbar if disabled
● Drag element to any part
of a layout
● Autoconnect generates
constraints against
parent layout
66
ConstraintLayout handles
1. Resizing handle
2. Constraint line and handle
3. Constraint handle
4. Baseline handle
67
Align elements by baseline
1. Click the baseline
constraint button
2. Drag from baseline to
other element's baseline
68
Attributes pane
69
Attributes pane view inspector
1. Vertical view size control specifies
layout_height
2. Horizontal view size control
specifies layout_width
3. Attributes pane close button
70
Layout_width and layout_height
layout_width and layout_height change with size controls
● match_constraint: Expands element to fill its parent
● wrap_content: Shrinks element to enclose content
● Fixed number of dp (density-independent pixels)
71
Set attributes
72
Set attributes example: TextView
73
Preview layouts
74
Create layout variant for landscape
75
Create layout variant for tablet
76
Event Handling
77
Events
78
Event Handlers
79
Attach in XML and implement in Java
Attach handler to view in Implement handler in Java
XML layout: activity:
android:onClick="showToast" public void showToast(View view) {
String msg = "Hello Toast!";
Toast toast = Toast.makeText(
this, msg, duration);
toast.show();
}
}
80
Alternative: Set click handler in Java
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String msg = "Hello Toast!";
Toast toast = Toast.makeText(this, msg, duration);
toast.show();
}
});
81
Resources and
measurements
82
Resources
83
Where are the resources in your project?
84
Refer to resources in code
● Layout:
R.layout.activity_main
setContentView(R.layout.activity_main);
● View:
R.id.recyclerview
rv = (RecyclerView) findViewById(R.id.recyclerview);
● String:
In Java: R.string.title
In XML: android:text="@string/title"
85
Measurements
● Density-independent Pixels (dp): for Views
● Scale-independent Pixels (sp): for text
86
2.1 Activities and Intents
87
Contents
● Activities
● Defining an Activity
● Starting a new Activity with an Intent
● Passing data between activities with extras
● Navigating between activities
88
Activities
(high-level view)
89
What is an Activity?
● An Activity is an application component
● Represents one window, one hierarchy of views
● Typically fills the screen, but can be embedded in other
Activity or a appear as floating window
● Java class, typically one Activity in one file
90
What does an Activity do?
● Represents an activity, such as ordering groceries,
sending email, or getting directions
● Handles user interactions, such as button clicks, text
entry, or login verification
● Can start other activities in the same or other apps
● Has a life cycle—is created, started, runs, is paused,
resumed, stopped, and destroyed
91
Examples of activities
92
Apps and activities
● Activities are loosely tied together to make up an app
● First Activity user sees is typically called "main activity"
● Activities can be organized in parent-child relationships in
the Android manifest to aid navigation
93
Layouts and Activities
● An Activity typically has a UI layout
● Layout is usually defined in one or more XML files
● Activity "inflates" layout as part of being created
94
Implementing
Activities
95
Implement new activities
1. Define layout in XML
2. Define Activity Java class
○ extends AppCompatActivity
96
1. Define layout in XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Shop for Food!" />
</RelativeLayout>
97
2. Define Activity Java class
98
3. Connect activity with layout
setContentView(R.layout.activity_main);
}
Resource is layout in this XML file
}
99
4. Declare activity in Android manifest
<activity android:name=".MainActivity">
100
4. Declare main activity in manifest
MainActivity needs to include intent-filter to start
from launcher
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
101
Intents
102
What is an intent?
An Intent is a description of an operation to be performed.
An Intent is an object used to request an action from
another app component via the Android system.
Intent Action
Android
System
103
What can intents do?
● Start an Activity
○ A button click starts a new Activity for text entry
○ Clicking Share opens an app that allows you to post a photo
● Start an Service
○ Initiate downloading a file in the background
● Deliver Broadcast
○ The system informs everybody that the phone is now charging
104
Explicit and implicit intents
Explicit Intent
● Starts a specific Activity
○ Request tea with milk delivered by Nikita
○ Main activity starts the ViewShoppingCart Activity
Implicit Intent
● Asks system to find an Activity that can handle this request
○ Find an open store that sells green tea
○ Clicking Share opens a chooser with a list of apps
105
Starting
Activities
106
Start an Activity with an explicit intent
To start a specific Activity, use an explicit Intent
1. Create an Intent
○ Intent intent = new Intent(this, ActivityName.class);
107
Start an Activity with implicit intent
To ask Android to find an Activity to handle your request,
use an implicit Intent
1. Create an Intent
○ Intent intent = new Intent(action, uri);
108
Implicit Intents - Examples
Show a web page
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
109
How Activities Run
● All Activity instances are managed by the Android runtime
● Started by an "Intent", a message to the Android runtime to
run an activity
User clicks MainActivity FoodListActivity OrderActivity
launcher icon What do you want to do? Choose food items...Next Place order
Intent: Start app Start main Intent: Shop Start choose Intent: order Start finish
Android activity Android food activity Android order activity
System System System
110
Sending and
Receiving Data
111
Two types of sending data with intents
● Data—one piece of information whose data location can
be represented by an URI
112
Sending and retrieving data
In the first (sending) Activity:
1. Create the Intent object
2. Put data or extras into that Intent
3. Start the new Activity with startActivity()
116
Get data from intents
● getData();
⇒ Uri locationUri = intent.getData();
● int getIntExtra (String name, int defaultValue)
⇒ int level = intent.getIntExtra("level", 0);
● Bundle bundle = intent.getExtras();
⇒ Get all the data at once as a bundle.
● See documentation for all
117
Returning data to the starting activity
1. Use startActivityForResult() to start the second Activity
2. To return data from the second Activity:
● Create a new Intent
● Put the response data in the Intent using putExtra()
● Set the result to Activity.RESULT_OK
or RESULT_CANCELED, if the user cancelled out
● call finish() to close the Activity
1. Implement onActivityResult() in first Activity
118
startActivityForResult()
startActivityForResult(intent, requestCode);
● Starts Activity (intent), assigns it identifier (requestCode)
● Returns data via Intent extras
● When done, pop stack, return to previous Activity, and
execute onActivityResult() callback to process returned
data
● Use requestCode to identify which Activity has "returned"
119
1. startActivityForResult() Example
120
2. Return data and finish second activity
// Create an intent
Intent replyIntent = new Intent();
121
3. Implement onActivityResult()
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) { // Identify activity
if (resultCode == RESULT_OK) { // Activity succeeded
String reply =
data.getStringExtra(SecondActivity.EXTRA_REPLY);
// … do something with the data
}}}
122
Navigation
123
Activity stack
● When a new Activity is started, the previous Activity
is stopped and pushed on the Activity back stack
● Last-in-first-out-stack—when the current Activity ends,
or the user presses the Back button, it is popped from the
stack and the previous Activity resumes
124
Activity Stack
After viewing shopping
cart, user decides to add
more items, then places
order.
OrderActivity
Place order
CartActivity CartActivity
View shopping cart View shopping cart
FoodListActivity FoodListActivity FoodListActivity
Choose food items Choose food items Choose food items
MainActivity MainActivity MainActivity MainActivity
What do you want to do? What do you want to do? What do you want to do? What do you want to do?
125
Two forms of navigation
Temporal or back navigation
● provided by the device's Back button
● controlled by the Android system's back stack
Ancestral or up navigation
● provided by the Up button in app's action bar
● controlled by defining parent-child relationships between
activities in the Android manifest
126
Back navigation
● Back stack preserves history of recently viewed screens
● Back stack contains all the Activity instances that have been
launched by the user in reverse order for the current task
● Each task has its own back stack
● Switching between tasks activates that task's back stack
127
Up navigation
● Goes to parent of current Activity
● Define an Activity parent in Android manifest
● Set parentActivityName
<activity
android:name=".ShowDinnerActivity"
android:parentActivityName=".MainActivity" >
</activity>
128
4.1 Buttons and clickable
images
129
Contents
● User interaction
● Buttons
● Clickable images
● Floating action button
● Common gestures
130
User interaction
131
Users expect to interact with apps
132
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
133
Buttons
134
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
135
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 Experiment:
(the Android logo) 2. Choose New > Vector Asset
136
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" />
137
Setting listener with onClick callback
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
138
Clickable
images
139
ImageView
● ImageView with android:onClick attribute
● Image for ImageView in app>src>main>res>drawable
folder in project
140
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"/>
141
4.2 Input Controls
142
Contents
143
Overview of
input Controls
144
Accepting user input
145
Examples of input controls
1. EditText
2. SeekBar
3. CheckBox
4. RadioButton
5. Switch
6. Spinner
146
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
147
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
148
View focus
149
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
150
Clickable versus focusable
151
Which View gets focus next?
152
Guiding users
153
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"
154
Set focus explicitly
155
Find the view with focus
● Activity.getCurrentFocus()
● ViewGroup.getFocusedChild()
156
Freeform text
and numbers
157
EditText for multiple lines of text
● EditText default
● Alphanumeric keyboard
● Suggestions appear
● Tapping Return (Enter) key starts
new line
Return key
158
Customize with inputType
159
EditText for message
● android:inputType
="textShortMessage"
● Single line of text
● Tapping Emoticons key changes
keyboard to emoticons
Emoticons
160
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
161
EditText for phone number entry
● android:inputType ="phone"
● Numeric keypad (numbers only)
● Tapping Done key advances focus
to next View
Done key
162
Getting text
163
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
164
4.3 Menus and pickers
165
Contents
● Overview
● App Bar with Options Menu
● Contextual menus
● Popup menus
● Dialogs
● Pickers
166
Overview
167
Types of Menus
1. App bar with options
menu
2. Context menu
3. Contextual action bar
4. Popup menu
168
Dialogs and pickers
1. Alert dialog
2. Date picker
3. Time picker
1 2 3
169
App Bar with
Options Menu
170
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
171
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
172
Adding Options
Menu
173
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
174
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" />
175
Inflate options menu
Override onCreateOptionsMenu() in Activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
176
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
177
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" />
178
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);
}
}
179
Contextual
Menus
180
What are contextual menus?
181
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
182
Floating
Context Menu
183
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
184
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"/>
185
Register a view to a context menu
186
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);
}
187
Implement onContextItemSelected()
onCreateContextMenu()
@Override method
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);
}
}
188
Contextual
Action Bar
189
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
190
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
191
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
192
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
193
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;
}
});
194
Implement mActionModeCallback
195
Implement onCreateActionMode
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
return true;
}
196
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.
}
197
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;
}
}
198
Implement onDestroyActionMode
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
199
Popup Menu
200
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
201
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
202
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"/>
203
Assign onClickListener to button
private ImageButton mButton =
(ImageButton) findViewById(R.id.button_popup);
In onCreate():
mButton.setOnClickListener(new View.OnClickListener() {
// define onClick
});
204
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();
}
205
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;
}
}
206
Dialogs
207
Dialogs
● Dialog appears on top,
interrupting flow of Activity
● Requires user action to dismiss
208
AlertDialog
AlertDialog can show:
1. Title (optional)
2. Content area
3. Action buttons
209
Build the AlertDialog
Use AlertDialog.Builder to build alert dialog and set
attributes:
210
Set the button actions
● alertDialog.setPositiveButton()
● alertDialog.setNeutralButton()
● alertDialog.setNegativeButton()
211
alertDialog code example
alertDialog.setPositiveButton(
"OK", newDialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User clicked OK button.
}
});
212
Pickers
213
Pickers
● DatePickerDialog
● TimePickerDialog
214
Pickers use fragments
● Use DialogFragment to show a picker
● DialogFragment is a window that floats
on top of Activity window
215
Introduction to fragments
● A Fragment is like a mini-Activity within an Activity
○ Manages its own own lifecycle
○ Receives its own input events
216
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
217
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
218