CHAPTER 4 : Interface Design &
Interaction
Subtopic
• Designing Interface and Interacting with
component.
• Standard input component
• Standard output component
• Interface layout design
• Menu control
Android Apps - Structure
• Android Code
• All the logic
• Resources
• Manifest
3
App Components
• Core building blocks of an app.
• Entry points for an app.
• Activities are “screens” with a UI.
• Services run a task in the background.
• Broadcast receivers deliver events to apps
outside of regular user flow.
• Content providers manage a pool of information.
4
Activities
• A single screen with a user interface.
• Most apps have multiple independent activities.
• E-mail: Show messages, compose, read.
• If allowed, other apps can start any activity.
• Camera app opens “Compose” activity to share photo.
• Activities control and link processes.
• Ensure the current process is not killed.
• Link to calling activities and maintain their process.
• Model state in case process is killed.
• Model flow between apps.
5
Services
• Entry point for running a background process.
• Playing music, sending files.
• Does not provide a direct UI.
• Can be started by an activity.
• Can maintain a notification to allow user interaction.
• Services without notifications can be killed if resources
are needed by OS.
• Bound services offer an API to the calling app.
• Maintained as long as needed, then killed.
6
Broadcast Receivers
• Allows OS to deliver events when the app is not
running.
• Listen to system-wide broadcast announcements.
• Respond to events like a photo being taken.
• Often notify users that an event has occurred.
• Often minimal, used as a gateway to launch
activities or services.
7
Content Providers
• Manages a shared set of app data.
• Other, allowed, apps can query or modify the data.
• Android has a Content Provider for contact data.
• An entry point into an app for publishing data items.
• Identified by a URI.
• Owning app wakes up when a URI is accessed.
• URIs provide a secure way to pass content.
• Content is locked and accessed through temporary permission.
8
Designing Interface and Interacting with
component.
Designing Activities
10
The Concept of Activities
• Rather than interacting with apps as atomic units,
Activities interact directly with Activities.
• Any Activity can serve as an entry point to app interaction
• An Activity has a UI, and is usually a single screen.
• An app may have a Settings Activity, a Select Photo
Activity, ...
• One Activity is the “main activity”.
• Launches when you click the icon.
• Activities must have minimal dependencies on
other Activities.
11
Activity Lifecycle
Activity dismissed,
configuration change
(e.g., rotation)
Other Activity in
foreground,
incoming phone
Activity no longer call, ...
visible (e.g., new
activity started)
12
App Architecture Activity code
manages state,
captures user input
Creates and presents
the on-screen layout.
Models process, load,
and store app data Data can also be
locally. loaded, stored, and
processed from
remote sources.
13
Navigation
• All apps have a fixed
start location.
• A stack of Activities
is maintained. When
you press back, you
pop from the stack.
• Also provide “up navigation”.
• (exit a chain to a set location)
• Define a parent activity in the manifest.
14
Activity Best Practices
• Activities should coordinate with Data Models to
retrieve a minimal amount of relevant data.
• Create independent, well-defined code modules.
• Make each module testable in isolation.
• Do not write code if an existing Activity does it.
• Use Models to persist fresh, relevant data.
• Assign one data source as the source of truth.
15
Interface Layouts Design
UI Design - Views and Layouts
• A layout (ViewGroup) defines
the structure of the UI.
• Containers that group one
or more widgets (View).
• A button, a text box.
• Many pre-defined types of
layouts (LinearLayout,
Constraint Layout).
• UI elements can be declared
in XML or in code.
17
UI Design - XML
Layout has two widgets,
which have no
constraints on each
other’s size or location Text box
containing a set
string
Button with a set
string.
18
UI Design - Attributes
• All View objects have a unique identifier.
• Integer assigned at compile time, mapped to a user-
specified variable: android:id=”@+id/my_button”
19
UI Design - Attributes
• LayoutParameters
• Inherited by Views contained
in that layout.
• Define how Views appear.
• All ViewGroups have a width and height.
• Each view must define width and height relative to this.
• wrap_content sizes view to its content.
• match_parent makes view as big as its parent
ViewGroup allows.
• Specify in dp (density-independent pixel units)
20
UI Design - Layouts
• Views are rectangles with left and top coordinates.
• Can get location with getLeft() and getTop()
• Defined relative to the parent.
• Size is defined in width and height.
• Measured width/height are how big the view wants to be.
• Drawing width/height are the actual size of the view on
screen, after layout constraints.
• These can differ.
21
UI Design - Common Layouts
Built from data using an
Adapter
22
UI Design - Responsive Design
• Android defines two characteristics for each
screen:
• Screen Size (physical size)
• Small, Normal, Large, XLarge
• Screen Density (density of pixels on screen)
• MDPI (~160dpi), HDPI (~240dpi), XHDPI (~320dpi), XXHDPI
(~480dpi), XXXHDPI (~640dpi)
• Apps are compatible with all screen sizes and
densities automatically, but this may not create a
good UX.
• Create specialized layouts, optimize images for density.
23
Creating a Flexible Layout
• ConstraintLayout allows position/size
specification based on spatial relationships
between views.
• All views move together as screen size changes.
• Easiest to create in Android Studio Layout Editor.
• Avoid hard-coded layout sizes.
• Use wrap_content, match_parent.
• Automatically adjusts based on size and orientation of
screen.
24
Create Stretchable Images
• Bitmaps stretch to the screen
size and density.
• This can cause blurring and
scaling artifacts.
• Nine-patch bitmaps add a 1px
border that indicates which
pixels can be stretched.
• Intersection between left/top
lines indicates the area that
can be stretched.
25
Menu control
Steps to create menus
1. Choose icons to be used
• Create your own in the required sizes
• Use the image asset wizard to choose one that is standard
2. Define the menu items in XML
3. Call setHasOptionsMenu(true); in onCreate() or
onCreateView()
4. Code onCreateOptionsMenu() to inflate the menu
5. Code the onOptionsItemSelected() menu to listen for and
handle selections
Option Menu Framework
Classes: [Link], [Link], [Link]
Regular Menu From XML
XML in file game_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="[Link]
<group android:id="@+id/menuGroup"> // Group of items tied together
<item android:id="@+id/new_game" android:title="@string/new" />
<item android:id="@+id/help" android:title="@string/help" />
<group>
</menu>
Java Code to include the menu
@Override public boolean onCreateOptionsMenu(Menu menu)
{ [Link](menu); // Allow for system menu items MenuInflater inflater =
getMenuInflater();
[Link]([Link].game_menu, menu);
return true; // Force menu to be visible
Note: Android calls onPrepareMenuOption } every time a menu is invoked.
Overriding this method enables dynamically changing menu items.
Menu Groups
• Definition: A sequence of items from a menu
• Purpose: Control all grouped items at once
• Examples:
– [Link](id, checkable, exclusive): Check selected items;
if exclusive, only one group item can be checked
– [Link](id, enabled): Control ghosted items
– [Link](id, visible): Show or hide the group items
– [Link](id): Remove all items from the group
Creating a Menu in Code
• Regular menu items
int group = Menu.CATEGORY_NONE, order=[Link], menuID = 99;
[Link](group, menuID++, order++, "append");
[Link](group, menuID++, order++, "clear");
• Secondary menu items
int group = Menu.CATEGORY_SECONDARY
int order=[Link], menuID = [Link];
[Link](group, menuID++, order++, "secondary item #1");
[Link](group, menuID++, order++, [Link].secItem2);
• Java Setup code
@Override public boolean onCreateOptionsMenu(Menu menu)
{ [Link](menu); // Allow for system menu items
addRegularMenuItems(menu); addSecondaryMenuItems(menu);
return true; // Force menu to show
}
Respond to Menu Item Selections
Android calls onOptionItemSelected method when an item is selected
@Override public boolean onOptionsItemSelected(MenuItem item)
{ switch ([Link]())
{ case [Link].new_game:
newGame();
return true; // consume this selection here
case [Link]:
showHelp();
return true; // consume this selection here
case [Link]:
[Link](Menu.CATEGORY_SECONDARY, true);
return true; // consume this selection here
default:
return [Link](item);
} }
Icon Menus
• In XML: android:icon="@drawable/ballons"
• In Code: [Link]([Link]);
• Restrictions
– Will not appear on expanded menu options (those which
show only when the more item is selected)
– Check marks are not supported
Submenus
• In XML: <item android:title="Outer Menu Item>
<menu><item> . . .</item></menu>
• In Code:
int base = [Link];
∙ ∙ ∙
SubMenu sub = [Link](base, item++ ,[Link], "submenu");
[Link](base, order++, menuID++, "sub item # 1");
[Link](base,order++, menuID++, [Link].subItem2 );
• Restrictions
– Icons work with submenus, but not with individual submenu items
– You cannot nest a submenu to a submenu
• Advantage: Android automatically controls the visibility
• Note: The order argument is optional; [Link] indicates a default order.
Context Menus
onContextItemSelected()
View
Context Menu Creation
• Ownership: view
• Creation: Activity
– Register in the activities onCreate method
@Override public void onCreate(Bundle savedInstanceState)
{ [Link](savedInstanceState);
setContentView([Link]);
TextView tv = (TextView)[Link]([Link]);
registerForContextMenu(tv); // Indicate that view has context menu
}
– Populate: (note: info can get position for complex views)
onCreateContextMenu(ContextMenu m, View v, ContextMenuInfo info)
– Listener: onContextItemSelected(MenuItem item)
Popup Menu
It displays when touching the image,
It disappears when selecting if selected or touching outside its
bounds
• Specify in an XML view declaration
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_overflow_holo_dark"
android:contentDescription="@string/descr_overflow_button"
android:onClick= "showPopup" />
• Activity code to display the popup
public void showPopup(View v)
{ PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = [Link]();
[Link]([Link], [Link]());
[Link]();
} // Note: [Link] refers to the XML menu declaration
Note: Listener attached with onMenuItemClick() method
Alternative
Menus
• Application menus items can launch content providers that provide an intent filter
in their manifest
• Content Providers expose data by defining a MIME type and a content URI access
point for other applications
• Example: (The application Employees maintains employee data)
1. MIME type: [Link]/[Link]
2. Other application can access the data by calling the Uri
content://[Link]/All access all employees or the Uri
content://[Link]/1 access a single employee instance
• An alternative menu item in an Application, when clicked, launches the content
provider using the Uri in an intent
End