UNIT4
UNIT4
21
Apps and activities
22
Layouts and Activities
23
Implementing
Activities
24
Implement new activities
1. Define layout in XML
2. Define Activity Java class
○ extends AppCompatActivity
25
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>
26
Creating an Activity
To create an activity, you must create a subclass of
Activity
In your subclass, you need to implement callback
methods that the system calls when the activity
transitions between various states of its lifecycle such as
when the activity is being created,stopped, resumed, or
destroyed.
• The two most important callback methods are:
• onCreate()
• onPause()
Methods in Activity
• onCreate() You must implement this method.
• The system calls this when creating your activity.
• Within your implementation, you should initialize the essential
components of your activity.
• Most importantly, this is where you must call setContentView()
to define the layout for the activity's user interface.
• onPause() The system calls this method as the first indication
that the user is leaving your activity (though it does not always
mean the activity is being destroyed).
• This is usually where you should commit any changes that
should be persisted beyond the current user session .
2. Define Activity Java class
29
3. Connect activity with layout
setContentView(R.layout.activity_main
);
}
} Resource is layout in this XML file
30
4. Declare activity in Android
manifest
<activity
android:name=".MainActivity">
31
4. Declare main activity in manifest
32
Activity life cycle
Other Methods
• There are several other lifecycle callback
methods :
• onResume()
• onStart()
• onStop()
• onDestroy()
Intents
35
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.
Originator App component
Intent Action
Android
System
36
What is an Intent?
• Intent is an intention to do something.
➢ Intent contains an action carrying some
information.
➢ Intent is used to communicate between
android components.
• To start an activity
• To start a service
• To deliver a broadcast.
What can intents do?
● Start activities
○ A button click starts a new activity for text entry
○ Clicking Share opens an app that allows you to post a photo
● Start services
○ Initiate downloading a file in the background
● Deliver broadcasts
○ The system informs everybody that the phone is now charging
38
Types of Intents?
• Explicit Intents
• Implicit Intents
Explicit Intents
• Used to launch a specific component like
activity or a service.
➢ In this case, android system directly
forwards this intent to that specific component.
➢ It is faster.
➢ Always use explicit intents if you know the
specific activity or service that performs
Implicit Intent
• Specifies an action that can invoke an app
on the device that can perform the action.
➢ Useful when your app can not perform the
action but other apps do and you let user to pick
up the app.
➢ Its possible that there may not be any app
that handles the implicit intent.
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
42
How Intents are received?
• Till now we have seen how intents are used to
invoke some other components. Now lets
explore how these components receive these
intents.
➢ Receiving Implicit Intents
➢ Receiving Explicit Intents
• Explicit Intents are directly delivered to target
as intent has the target component class
specified in it.
Receiving Implicit Intents
45
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);
46
Start an Activity with implicit intent
47
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);
48
How Activities Run
● All activities are managed by the Android runtime
● Started by an "intent", a message to the Android
runtime to run an activity
49
Sending and
Receiving Data
50
Two types of sending data with
intents
● Data—one piece of information whose data
location can be represented by an URI
51
Sending and retrieving data
Uri.parse("http://www.google.com"));
54
Navigation
55
Activity stack
56
Activity Stack
After viewing vit
y
ti
c r
shopping cart, user e
d o
rA rde
Or ace
decides to add more Pl
items, then places t
order. i ty g car
tiv in vity ng car
t
r tA c op p cti i
Ca w sh tA p
Car shop
V ie OrderActivity V ie
w
Place order
ty
CartActivity CartActivity d L i stActivi ms
Foo ite
View shopping cart View shopping cart
h o o s e food
C
FoodListActivity FoodListActivity FoodListActivity
Choose food items Choose food items Choose food items
57
Two forms of navigation
Ancestral or up navigation
● provided by the app's action bar
● controlled by defining parent-child
relationships between activities in the
Android manifest
58
Back navigation
● Back stack preserves history of recently viewed screens
● Back stack contains all the activities 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
● Launching an activity from the home screen starts a new task
● Navigate between tasks with the overview or recent tasks screen
59
Up navigation
● Goes to parent of current activity
● Define an activity's parent in Android manifest
● Set parentActivityName
<activity
android:name=".ShowDinnerActivity"
android:parentActivityName=".MainActivity" >
</activity>
60
View types
• Adapter View
• List View
• Picker view
Adapter View
• The ListView and GridView are subclasses of AdapterView
• They can be populated by binding them to an Adapter, which retrieves
data from an external source and creates a View that represents each data
entry.
• An Adapter View can be used to display large sets of data efficiently in
form of List or Grid etc, provided to it by an Adapter.
• An Adapter View is capable of displaying millions of items on the User
Interface
• While keeping the memory and CPU usage very low and without any
noticeable lag
How it works?
• It only renders those View objects which are currently on-
screen or are about to some on-screen.
• Hence no matter how big your data set is, the Adapter View
will always load only 5 or 6 or maybe 7 items at once,
depending upon the display size.
• Hence saving memory.
• It also reuses the already created layout to populate data
items as the user scrolls, hence saving the CPU usage.
• Suppose you have a dataset, like a String array
with the following contents.
• String days[] = {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"};
• an Adapter takes the data from this array and creates a View
from this data and then, it gives this View to an AdapterView.
• The AdapterView then displays the data in the way you want.
• You can display it vertically (ListView), or in rows and columns
(GridView), or in drop-down menu (Spinners), etc.
List View
• A view which groups several items and display
them in vertical scrollable list.
• The list items are automatically inserted to
the list using an Adapter that pulls content
from a source such as an array or database.
List View
Picker view
• Android provides controls for the user to pick
a time or pick a date as ready-to-use dialogs
• Each picker provides controls for selecting
each part of the time (hour, minute, AM/PM)
or date (month, day, year).
• Using these pickers helps ensure that your
users can pick a time or date that is valid,
formatted correctly, and adjusted to the user's
locale.
Menus
75
What is the App Bar?
Bar at top of each screen—(usually) the same for
all screens
77
Adding Options
Menu
78
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
79
Create menu resource
1. Create menu resource directory
2. Create XML menu resource (menu_main.xml)
3. Add an entry for each menu item
<item android:id="@+id/option_settings"
android:title="@string/settings" />
<item android:id="@+id/option_toast"
android:title="@string/toast" />
80
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 81
Add menu item attributes
<item android:id="@+id/action_order"
android:icon="@drawable/ic_toast_dark"
android:title="@string/toast"
android:titleCondensed="@string/toast_condensed"
android:orderInCategory="1"
app:showAsAction="ifRoom" />
82
Layouts in Android
• Layouts define the arrangement of views.
• • Android layouts are defined mostly in XML.
• • Various properties of Layouts can be set
• using XML attributes.
Types Of Layout
• • Linear Layout
• • Relative Layout
• • Absolute Layout
• • Table Layout
Orientation:
Orientation
Fill-model
weight
Gravity
• android:layout_gravity=”right”
padding
Examples
RelativeLayout
Relative Layout attributes
Relative Layout
Relative Layout
TableLayout
Table Layout
Table Layout
TableLayout Example
Absolute Layout
Absolute Layout