Chapter-2 2
Chapter-2 2
COMPUTING
Mobile Application Development.
CAH-655
DISCOVER . LEARN .
EMPOWER
Importance
• Understanding different User Interface Controls.
11/28/2024
2
Topic Objectives
• To work with different User Interface Controls.
11/28/2024
3
1.2 Layouts and resources for the UI
4
Contents
● Views, view groups, and view hierarchy
● The layout editor and ConstraintLayout
● Event handling
● Resources and measurements
5
Views
6
Everything you see is a view
If you look at your mobile device,
every user interface element that you see is
a View.
Views
7
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)
8
Examples of view subclasses
Button CheckBox
EditText RadioButton
Slider Switch
9
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
10
Create views and layouts
11
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
12
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"
/>
13
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"
14
Create View in Java code
context
In an Activity:
15
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);
16
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
17
ViewGroup and
View hierarchy
18
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
19
ViewGroups for layouts
Layouts
● are specific types of ViewGroups (subclasses of ViewGroup
)
● contain child views
● can be in a row, column, grid, table, absolute
20
Common Layout Classes
21
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
22
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
23
Hierarchy of viewgroups and views
24
View hierarchy and screen layout
25
View hierarchy in the layout editor
26
Layout created in XML
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
... />
<TextView
... />
<Button
... />
</LinearLayout
27
Layout created in Java Activity code
LinearLayout linearL = new LinearLayout(this);
linearL.setOrientation(LinearLayout.VERTICAL);
linearL.addView(myText);
setContentView(linearL);
28
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);
29
Best practices for view hierarchies
● Arrangement of view hierarchy affects app
performance
● Use smallest number of simplest views possible
● Keep the hierarchy flat—limit nesting of views and
view groups
30
The layout
editor and
Constraint
Layout
31
The layout editor with ConstraintLayout
32
What is ConstraintLayout?
33
Layout editor main toolbar
34
ConstraintLayout toolbar in layout editor
35
Autoconnect
● Enable Autoconnect in
toolbar if disabled
● Drag element to any part of
a layout
● Autoconnect generates
constraints against parent
layout
36
ConstraintLayout handles
1. Resizing handle
2. Constraint line and
handle
3. Constraint handle
4. Baseline handle
37
Align elements by baseline
1. Click the baseline
constraint button
2. Drag from baseline to
other element's
baseline
38
Attributes pane
● Click the Attributes tab
● Attributes pane
includes:
○ Margin controls for
positioning
○ Attributes such as
layout_width
39
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
40
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)
41
Set attributes
42
Set attributes example: TextView
43
Preview layouts
44
Create layout variant for landscape
45
Create layout variant for tablet
46
Layouts
47
Layout Example
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="…"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
48
Loading XML file
49
Attributes
android:id="@+id/my_button"
51
Layout Managers
52
Linear Layout
</LinearLayout>
53
Table Layout
• extension of LinearLayout
• This layout structures its child controls into
rows and columns
<TableLayout xmlns:android=“…"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow>
<TextView … />
<EditText … />
</TableRow>
<TextView … />
<EditText … />
</TableRow>
</TableLayout>
54
Table Layout
55
Table Layout
<RelativeLayout xmlns:android=“…"
<TextView android:id="@+id/userNameLbl"
android:layout_alignParentTop="true" />
<EditText android:id="@+id/userNameText"
android:layout_below="@id/userNameLbl" />
<TextView android:id="@+id/pwdLbl"
android:layout_below="@id/userNameText" />
<EditText android:id="@+id/pwdText"
android:layout_below="@id/pwdLbl"/>
<TextView android:id="@+id/pwdHintLbl"
android:layout_below="@id/pwdText"/>
<TextView android:id="@+id/disclaimerLbl"
android:layout_alignParentBottom="true" />
</RelativeLayout>
56
Absolute Layout
DESIGN PHILOSOPHY:
57
Input Controls
• Input controls are the interactive components in your app's
user interface.
• Android provides a wide variety of controls you can use in
your UI, such as buttons, text fields, seek bars, check box,
zoom buttons, toggle buttons, and many more.
58
Features of Android
59
Features of Android
60
TextView UI
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</LinearLayout>
61
EditText UI
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editInp"
android:id="@+id/editDig“ />
</LinearLayout>
62
Button UI
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="109dp"
android:text="ADD"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
63
RadioButton UI
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=“Male"
android:layout_marginTop="20dp" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=“Female" />
64
CheckBox UI
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:checked="true"
android:text="Dog" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cat" />
65
Spinner UI
<Spinner
android:id="@+id/spinner"
android:layout_width="149dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp" />
66
Dimension
Intent Action
Android
System
68
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
69
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
70
Starting
Activities
71
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);
72
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);
73
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, 74
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
75
Sending and
Receiving Data
76
Two types of sending data with intents
● Data—one piece of information whose data location can
be represented by an URI
77
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()
78
Putting a URI as intent data
// A web page URL
intent.setData(
Uri.parse("http://www.google.com"));
"com.example.android.twoactivities.extra.MESSAGE"
;
83
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"
84
1. startActivityForResult() Example
85
2. Return data and finish second activity
// Create an intent
Intent replyIntent = new Intent();
86
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
}}}
87
Contents
● Intent—recap
● Implicit Intent overview
● Sending an implicit Intent
● Receiving an implicit Intent
88
Implicit Intent
overview
89
What you do with an implicit Intent
90
What system does with implicit Intent
● Android runtime matches the implicit intent request with
registered intent handlers
● If there are multiple matches, an App Chooser will open to let
the user decide
91
How does implicit Intent work?
1. The Android Runtime keeps a list of registered Apps
2. Apps have to register via AndroidManifest.xml
3. Runtime receives the request and looks for matches
4. Android runtime uses Intent filters for matching
5. If more than one match, shows a list of possible matches and
lets the user choose one
6. Android runtime starts the requested activity
92
App Chooser
93
Sending an
implicit Intent
94
Sending an implicit Intent
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);
if (intent.resolveActivity(getPackageManager()) !=
null) {
startActivity(intent);
}
96
Sending an implicit Intent with data URI
1. Create an Intent for action
Intent intent = new Intent(Intent.ACTION_DIAL);
● Uri.parse("tel:8005551234")
● Uri.parse("geo:0,0?q=brooklyn%20bridge%2C%20brooklyn%2C
%20ny")
● Uri.parse("http://www.android.com");
Uri documentation
98
Implicit Intent 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, 99
Sending an implicit Intent with extras
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
2. Put extras
String query = edittext.getText().toString();
intent.putExtra(SearchManager.QUERY, query));
101
Sending an implicit Intent with type and
category
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
103
Common actions for an implicit Intent
Common actions include:
● ACTION_SET_ALARM
● ACTION_IMAGE_CAPTURE
● ACTION_CREATE_DOCUMENT
● ACTION_SENDTO
● and many more
104
Apps that handle common actions
Common actions are usually handled by installed
apps (both system apps and other apps), such as:
105
Receiving an
Implicit Intent
106
Register your app to receive an Intent
● Declare one or more Intent filters for the Activity in
AndroidManifest.xml
● Filter announces ability of Activity to accept an implicit Intent
● Filter puts conditions on the Intent that the Activity accepts
107
Intent filter in AndroidManifest.xml
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
108
Intent filters: action and category
110
An Activity can have multiple filters
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
...
</intent-filter>
<intent-filter>
<action
android:name="android.intent.action.SEND_MULTIPLE"/>
...
</intent-filter> An Activity can have several
</activity> filters 111
A filter can have multiple actions & data
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<action
android:name="android.intent.action.SEND_MULTIPLE"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
<data android:mimeType="video/*"/>
</intent-filter>
112
Intent Types
113
Service and
Service Life
Cycle
114
Service
• Don’t have UI
• Network Transactions
• Play Music
stopService()
stopService()
onDestroy()
onDestroy()
Service
Servicefinished
finished
Fig. Started Service Lifecycle
Forms of Service: Bound
bindService()
Bounded
startService()
• Offers client-server interface that Service
onCreate()
onCreate()
allows components to interact with
onBind()
onStart()
the service
Service
Service is
is running
running onRebind()
• Client send requests and get results
onUnbind()
stopService()
• Started with bindService( )
onDestroy()
onDestroy()
• Ends when all clients end
Service
Servicefinished
finished
• Although services are separate from the UI, they still run on the
main thread by default. (except IntentService)
• Offload CPU-intensive work to a separate thread within the
service.
Updating the App
• If the service can’t access the UI, how do you update the app to
show the result?
• Use a broadcast receiver.
Foreground Services
@override
try{
// Do some work
}
Services
130
Content
Provider
131
Content
• Content Provider
• Content Resolver
133
Content Provider
• Allows you to fetch the data that app requests from a repository
145
Broadcast Receivers
Implementation
• A receiver can be registered via the AndroidManifest.xml
file.
• Alternatively to this static registration, you can also register
a receiver dynamically via the Context.registerReceiver()
method.
• The implementing class for a receiver extends the
BroadcastReceiver class.
• If the event for which the broadcast receiver has registered
happens, the onReceive() method of the receiver is called
by the Android system.
146
Broadcast
Intents
Broadcast vs. Activity
android.intent.action.BOOT_COMPLETED
• When the wifi state changes
android.net.wifi.WIFI_STATE_CHANGED
Custom broadcasts
sendBroadcast() method—asynchronous
sendOrderedBroadcast()—synchronously
android.example.com.CUSTOM_ACTION
Implementing Broadcast
Receivers
• Subclass BroadcastReceiver
• Implement onReceive() method
• Register to receive broadcast
• Statically, in AndroidManifest
• Dynamically, with registerReceiver()
File > New > Other >
BroadcastReceiver
public class CustomReceiver extends BroadcastReceiver {
public CustomReceiver() {
}
@Override
public void onReceive(Context context, Intent intent)
{
// TODO: This method is called when the
BroadcastReceiver
// is receiving an Intent broadcast.
throw new UnsupportedOperationException("Not yet
implemented");
}
Register in Manifest
<receiver
android:name=".CustomReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Available Intents
● ACTION_TIME_TICK ● ACTION_PACKAGE_DATA_CLEARED
● ACTION_TIME_CHANGED ● ACTION_PACKAGES_SUSPENDED
● ACTION_TIMEZONE_CHANGED ● ACTION_PACKAGES_UNSUSPENDED
● ACTION_BOOT_COMPLETED ● ACTION_UID_REMOVED
● ACTION_PACKAGE_ADDED ● ACTION_BATTERY_CHANGED
● ACTION_PACKAGE_CHANGED ● ACTION_POWER_CONNECTED
● ACTION_PACKAGE_REMOVED ● ACTION_POWER_DISCONNECTED
● ACTION_PACKAGE_RESTARTED ● ACTION_SHUTDOWN
Custom Broadcast
● Sender and receiver must agree on unique name for intent (action
name)
● Define in activity and broadcast receiver
"com.example.android.powerreceiver.ACTION_CUSTOM_
BROADCAST";
Send Custom Broadcast
Intent customBroadcastIntent =
new Intent(ACTION_CUSTOM_BROADCAST);
LocalBroadcastManager.getInstance(this)
.sendBroadcast(customBroadcastIntent);
Destroy
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mReceiver);
super.onDestroy();
}
Implement onReceive()
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
switch (intentAction){
case Intent.ACTION_POWER_CONNECTED:
break;
case Intent.ACTION_POWER_DISCONNECTED:
break;
}
}
References
• https://www.youtube.com/watch?v=XXVsL3njoCQ
• https://codelabs.developers.google.com/codelabs/android-training-
broadcast-receivers/index.html?index=..%2F..android-training#1
• https://www.tutorialspoint.com/android/android_broadcast_receivers.htm
References
• https://www.youtube.com/watch?v=ROk-
YrZKYCg&list=PLlyCyjh2pUe9wv-hU4my-
Nen_SvXIzxGB&index=46&t=0s
• https://developer.android.com/guide/components/fundamentals
• https://developer.android.com/courses/fundamentals-training/overview-v2
• https://www.tutorialspoint.com/
References
• https://www.youtube.com/watch?v=fNVMqACYPnQ&t=3s
• https://developer.android.com/guide/topics/providers/content-providers
• https://www.tutorialspoint.com/android/android_content_providers.htm
BIBLIOGRAPHY
Text Books-
• Android Programming for Beginners by John Horton
• Reto Meier, “Profesional Android 4 Aplication Development” ,
John Wiley& Sons, Inc, 2012.
Reference Material-
• Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi
Nakamura, “Programming Android”, O’Reily boks
11/28/2024 164
Thank You
11/28/2024
165