0% found this document useful (0 votes)
447 views44 pages

UNIT-2 Activities, Fragments and Intents

This document provides an overview of activities, intents, and fragments in Android. It discusses: - Activities represent screens in an app and have a lifecycle of events like onCreate and onStart. - Intents are messages used to start activities, services, and broadcast receivers both within and between apps. They can specify actions like viewing a webpage or starting an activity. - Fragments are reusable UI components that can be added dynamically to activities. They allow modularizing an activity's UI into sections.

Uploaded by

Abhay Pawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
447 views44 pages

UNIT-2 Activities, Fragments and Intents

This document provides an overview of activities, intents, and fragments in Android. It discusses: - Activities represent screens in an app and have a lifecycle of events like onCreate and onStart. - Intents are messages used to start activities, services, and broadcast receivers both within and between apps. They can specify actions like viewing a webpage or starting an activity. - Fragments are reusable UI components that can be added dynamically to activities. They allow modularizing an activity's UI into sections.

Uploaded by

Abhay Pawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT-02

Activities, Fragments and Intents


TOPICS
• Activities, Fragments and Intents
2.1. Introduction to Activities
2.2. Activity Lifecycle
2.3. Introduction to Intents
2.4. Linking Activities using Intents
2.5. Calling built-in applications using Intents
2.6. Introduction to Fragments
2.7. Adding Fragments Dynamically
2.8. Lifecycle of Fragment
2.9. Interaction between Fragments
Introduction to Activities
• An application can have zero or more activities.
• Typically, applications have one or more activities, and the main aim
of an activity is to interact with the user.
• From the moment an activity appears on the screen to the moment it is
hidden, it goes through a number of stages, known as an activity’s life
cycle.
Introduction to Activities
• To create an activity, you create a Java class that extends the Activity base class:
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity


{
/** Called when the activity is first created.
*/ @Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
• Your activity class would then load its UI component using the XML file defined in
your res/layout folder. In this example, you would load the UI from the main.xml file:
setContentView(R.layout.main);
Activity:
• The Activity base class defines a series of events that governs the life cycle of an
activity. The Activity class defines the following events:
• onCreate() — Called when the activity is first created
• onStart() — Called when the activity becomes visible to the user
• onResume() — Called when the activity starts interacting with the user
• onPause() — Called when the current activity is being paused and the previous
activity is being resumed
• onStop() — Called when the activity is no longer visible to the user
• onDestroy() — Called before the activity is destroyed by the system (either manually
or by the system to conserve memory)
• onRestart() — Called when the activity has been stopped and is restarting again
• By default, the
activity created for
you contains the
onCreate() event.
Within this event
handler is the code
that helps to
display the UI
elements of your
screen.
Introduction to Intent
• Intents are used as a message-passing mechanism that works both
within your application and between applications.
• You can use Intents to do the following: Explicitly start a particular
Service or Activity using its class name Start an Activity or Service to
perform an action with (or on) a particular piece of data ‰ Broadcast
that an event has occurred You can use Intents to support interaction
among any of the application components installed on an Android
device, no matter which application they’re a part of.
• This turns your device from a platform containing a collection of
independent components into a single, interconnected system.
• One of the most common uses for Intents is to start new Activities,
either explicitly (by specifying the class to load) or implicitly (by
requesting that an action be performed on a piece of data).
Introduction to Intent
• In the latter case the action does not need to be performed by an
Activity within the calling application.
• You can also use Intents to broadcast messages across the system.
Applications can register Broadcast Receivers to listen for, and react
to, these Broadcast Intents.
• This enables you to create event-driven applications based on internal,
system, or third-party application events.
• Android broadcasts Intents to announce system events, such as
changes in Internet connectivity or battery charge levels.
Introduction to Intent
• The native Android applications, such as the Phone Dialer and SMS Manager,
simply register components that listen for specific Broadcast Intents — such as
“incoming phone call” or “SMS message received” — and react accordingly.
• As a result, you can replace many of the native applications by registering
Broadcast Receivers that listen for the same Intents.
• Using Intents, rather than explicitly loading classes, to propagate actions —
even within the same application — is a fundamental Android design principle.
• It encourages the decoupling of components to allow the seamless replacement
of application elements. It also provides the basis of a simple model for
extending an application’s functionality.
Introduction to Intent
• Android Intent is the message that is passed between components
such as activities, content providers, broadcast receivers, services etc.
• It is generally used with startActivity() method to invoke activity,
broadcast receivers etc.
• The dictionary meaning of intent is intention or purpose. So, it can
be described as the intention to do action
• The LabeledIntent is the subclass of android.content.Intent class.
Introduction to Intent
• Android intents are mainly used to:
• Start the service
• Launch an activity
• Display a web page
• Display a list of contacts
• Broadcast a message
• Dial a phone call etc.
Intents
• An intent is an abstract description of an operation to be performed.
• It can be used with Context#startActivity(Intent) to launch an
Activity, broadcastIntent to send it to any interested
BroadcastReceiver components, and Context.startService(Intent) or
Context.bindService(Intent, ServiceConnection, int) to communicate
with a background Service.
• Syntax:
• Intent intent=new Intent(Intent.ACTION_VIEW);
startActivity(intent);
Intents
• An Intent provides a facility for performing late runtime binding
between the code in different applications.
• Its most significant use is in the launching of activities, where it can
be thought of as the glue between activities.
• It is basically a passive data structure holding an abstract description
of an action to be performed.
Types of Android Intents
• There are two types of intents in android: implicit and explicit.

• Implicit Intent
• Implicit Intent doesn't specify the component. In such case, intent
provides information of available components provided by the system that
is to be invoked.
• For example, you may write the following code to view the
webpage.

Syntax:
Intent intent=new Intent(Intent.ACTION_VIEW);  
intent.setData(Uri.parse("http://www.example.com"));  
startActivity(intent);  
Types of Android Intents
• Explicit Intent
• Explicit Intent specifies the
component. In such case, intent
provides the external class to be
invoked.

• Syntax:
Intent i = new Intent(getApplicationContext
(), ActivityTwo.class);  
startActivity(i);  
Intent Structure
• The primary pieces of information in an intent are: action -- The
general action to be performed, such as ACTION_VIEW,
ACTION_EDIT, ACTION_MAIN, etc. data -- The data to operate on,
such as a person record in the contacts database, expressed as a Uri.
Intent Structure

• Some examples of action/data pairs are:


• ACTION_VIEW content://contacts/people/1 -- Display information about the person whose
identifier is "1". ACTION_DIAL content://contacts/people/1 -- Display the phone dialer with
the person filled in.
• ACTION_VIEW tel:123 -- Display the phone dialer with the given number filled in. Note
how the VIEW action does what is considered the most reasonable thing for a particular URI.
• ACTION_DIAL tel:123 -- Display the phone dialer with the given number filled in.
• ACTION_EDIT content://contacts/people/1 -- Edit information about the person whose
identifier is "1". ACTION_VIEW content://contacts/people/ -- Display a list of people, which
the user can browse through.
• This example is a typical top-level entry into the Contacts application, showing you the list of
people. Selecting a particular person to view would result in a new intent { ACTION_VIEW
content://contacts/people/N } being used to start an activity to display that person.
Intent Structure
• ACTION_MAIN with category CATEGORY_HOME -- Launch the home screen.
• ACTION_GET_CONTENT with MIME type vnd.android.cursor.item/phone --
Display the list of people's phone numbers, allowing the user to browse through
them and pick one and return it to the parent activity. ACTION_GET_CONTENT
with MIME type */* and category CATEGORY_OPENABLE -- Display all
pickers for data that can be opened with ContentResolver#openInputStream(Uri),
allowing the user to pick one of them and then some data inside of it and
returning the resulting URI to the caller.
• This can be used, for example, in an e-mail application to allow the user to pick
some data to include as an attachment.
Uses of Intent in Android
• To start an Activity An Activity represents a single screen in an app. You
can start a new instance of an Activity by passing an Intent to
startActivity().
• The Intent describes the activity to start and carries any necessary data
along.
• To start a Service A Service is a component that performs operations in
the background and does not have a user interface.
• You can start a service to perform a one-time operation(such as
downloading a file) by passing an Intent to startService().
• The Intent describes which service to start and carries any necessary data.
Uses of Intent in Android
• To deliver a Broadcast A broadcast is a message that any app can
receive.
• The system delivers various broadcasts for system events, such as
when the system boots up or the device starts charging.
• You can deliver a broadcast to other apps by passing an Intent to
sendBroadcast() or sendOrderedBroadcast().
Introduction to Fragments:
• A Fragment is a piece of an activity which enable more modular activity
design. It will not be wrong if we say, a fragment is a kind of sub-activity.
• Following are important points about fragment −
• A fragment has its own layout and its own behaviour with its own life cycle callbacks.
• You can add or remove fragments in an activity while the activity is running.
• You can combine multiple fragments in a single activity to build a multi-pane UI.
• A fragment can be used in multiple activities.
• Fragment life cycle is closely related to the life cycle of its host activity which means
when the activity is paused, all the fragments available in the activity will also be
stopped.
• A fragment can implement a behaviour that has no user interface component.
• Fragments were added to the Android API in Honeycomb version of Android which
API version 11.
Introduction to Fragments:
• A Fragment is a piece of an activity which enable more modular activity
design. A fragment encapsulates functionality so that it is easier to reuse
within activities and layouts.
Android devices exists in a variety of screen sizes and densities.
Fragments simplify the reuse of components in different layouts and
their logic. You can build single-pane layouts for handsets (phones) and
multi-pane layouts for tablets. You can also use fragments also to support
different layout for landscape and portrait orientation on a smartphone.
• The below image shows how two UI modules defined by fragments can
be combined into one activity for a tablet design but separated for a
handset design.
Fragments
• You create fragments by extending Fragment class and You can insert a
fragment into your activity layout by declaring the fragment in the activity's
layout file, as a <fragment> element.
• Prior to fragment introduction, we had a limitation because we can show only
a single activity on the screen at one given point in time. So we were not able
to divide device screen and control different parts separately. But with the
introduction of fragment we got more flexibility and removed the limitation
of having a single activity on the screen at a time. Now we can have a single
activity but each activity can comprise of multiple fragments which will have
their own layout, events and complete life cycle.
• Following is a typical example of how two UI modules defined by fragments
can be combined into one activity for a tablet design, but separated for a
handset design
Fragments
• The application can embed two
fragments in Activity A, when
running on a tablet-sized device.
• However, on a handset-sized
screen, there's not enough room for
both fragments, so Activity A
includes only the fragment for the
list of articles, and when the user
selects an article, it starts Activity
B, which includes the second
fragment to read the article.
Fragment Life Cycle
• Android
fragments have
their own life
cycle very
similar to an
android
activity. This
section briefs
different stages
of its life cycle.
Fragment Life Cycle
• onAttach()The fragment instance is associated with an activity instance.The
fragment and the activity is not fully initialized. Typically you get in this
method a reference to the activity which uses the fragment for further
initialization work.
• onCreate() The system calls this method when creating the fragment. You
should initialize essential components of the fragment that you want to retain
when the fragment is paused or stopped, then resumed.
• onCreateView() The system calls this callback when it's time for the fragment
to draw its user interface for the first time. To draw a UI for your fragment,
you must return a View component from this method that is the root of your
fragment's layout. You can return null if the fragment does not provide a UI.
Fragment Life Cycle
• onActivityCreated() The onActivityCreated() is called after the onCreateView() method
when the host activity is created. Activity and fragment instance have been created as
well as the view hierarchy of the activity. At this point, view can be accessed with the
findViewById() method. example. In this method you can instantiate objects which
require a Context object
• onStart() The onStart() method is called once the fragment gets visible.
• onResume() Fragment becomes active.
• onPause() The system calls this method as the first indication that the user is leaving the
fragment. This is usually where you should commit any changes that should be persisted
beyond the current user session.
• onStop() Fragment going to be stopped by calling onStop()
• onDestroyView() Fragment view will destroy after call this method
• onDestroy() onDestroy() called to do final clean up of the fragment's state but Not
guaranteed to be called by the Android platform.
Use OF Fragments
• This involves number of simple steps to create Fragments.
• First of all decide how many fragments you want to use in an activity. For
example let's we want to use two fragments to handle landscape and portrait
modes of the device.
• Next based on number of fragments, create classes which will extend
the Fragment class. The Fragment class has above mentioned callback
functions. You can override any of the functions based on your requirements.
• Corresponding to each fragment, you will need to create layout files in XML
file. These files will have layout for the defined fragments.
• Finally modify activity file to define the actual logic of replacing fragments
based on your requirement.
Types of Fragments
• Basically fragments are divided as three stages as shown below.
• Single frame fragments − Single frame fragments are using for hand
hold devices like mobiles, here we can show only one fragment as a
view.
• List fragments − fragments having special list view is called as list
fragment
• Fragments transaction − Using with fragment transaction. we can
move one fragment to another fragment.
Single frame fragments 
• Single frame fragment is designed for small screen devices such as
hand hold devices(mobiles) and it should be above android 3.0
version.
• Example
• This example will explain you how to create your own Fragments.
Here we will create two fragments and one of them will be used when
device is in landscape mode and another fragment will be used in case
of portrait mode. So let's follow the following steps to similar to what
we followed while creating Hello World Example −
Single frame fragments 
1. You will use Android StudioIDE to create an Android application and name it
as MyFragments under a package com.example.myfragments, with blank Activity.
2. Modify main activity file MainActivity.java as shown below in the code. Here we will
check orientation of the device and accordingly we will switch between different
fragments.
3. Create a two java files PM_Fragment.java and LM_Fragement.java under the
package com.example.myfragments to define your fragments and associated methods.
4. Create layouts files res/layout/lm_fragment.xml and res/layout/pm_fragment.xml and
define your layouts for both the fragments.
5. Modify the default content of res/layout/activity_main.xml file to include both the
fragments.
6. Define required constants in res/values/strings.xml file
7. Run the application to launch Android emulator and verify the result of the changes
done in the application.
List fragments 
• Static library support version of
the framework's ListFragment.
Used to write apps that run on
platforms prior to Android 3.0.
When running on Android 3.0
or above, this implementation
is still used.
• The basic implementation of
list fragment is for creating
list of items in fragments
List fragments 
• Example
• This example will explain you how to create your own list fragment based
on arrayAdapter. So let's follow the following steps to similar to what we
followed while creating Hello World
1. You will use Android Studio to create an Android application and name it
as SimpleListFragment under a
package com.example.tutorialspoint7.myapplication, with blank Activity.
2. Modify the string file, which has placed at res/values/string.xml to add new string
constants
3. Create a layout called list_fragment.xml under the directory res/layout to define
your list fragments. and add fragment tag(<fragment>) to your activity_main.xml
4. Create a myListFragment.java, which is placed at java/myListFragment.java and
it contained onCreateView(),onActivityCreated() and OnItemClickListener()
5. Run the application to launch Android emulator and verify the result of the
changes done in the application.
Fragments transaction 
• Activity and Fragment transitions in Lollipop are built on top of a
relatively new feature in Android called Transitions. Introduced in
KitKat, the transition framework provides a convenient API for
animating between different UI states in an application. The framework
is built around two key concepts: scenes and transitions. A scene
defines a given state of an application's UI, whereas a transition
defines the animated change between two scenes.
• When a scene changes, a Transition has two main responsibilities −
• Capture the state of each view in both the start and end scenes.
• Create an Animator based on the differences that will animate the
views from one scene to the other.
Fragments transaction 
• Example
1. You will use Android Studio to create an Android application and name it
as fragmentcustomanimations under a package com.example.fragmentcustomanimations,
with blank Activity.
2. Modify the activity_main.xml, which has placed at res/layout/activity_main.xml to add a
Text View
3. Create a layout called fragment_stack.xml.xml under the directory res/layout to define
your fragment tag and button tag
4. Create a folder, which is placed at res/ and name it as animation and add
fragment_slide_right_enter.xml
fragment_slide_left_exit.xml, ,fragment_slide_right_exit.xml and
fragment_slide_left_enter.xml
5. In MainActivity.java, need to add fragment stack, fragment manager, and onCreateView()
6. Run the application to launch Android emulator and verify the result of the changes done
in the application.
Android Fragments
• Android Fragment is the part of activity, it is also known as sub-activity. There can be
more than one fragment in an activity.
• Fragments represent multiple screen inside one activity.

• Android fragment lifecycle is affected by activity lifecycle because fragments are


included in activity.

• Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.

• The FragmentManager class is responsible to make interaction between fragment objects.


Android Fragment Lifecycle
• The lifecycle of android
fragment is like the
activity lifecycle. There
are 12 lifecycle methods
for fragment.
Android Fragment Lifecycle Methods
• onAttach(Activity) :
• It is called only once when it is attached with activity.
• onCreate(Bundle)
• It is used to initialize the fragment.
• onCreateView(LayoutInflater, ViewGroup, Bundle)
• creates and returns view hierarchy.
• onActivityCreated(Bundle)
• It is invoked after the completion of onCreate() method.
• onViewStateRestored(Bundle)
• It provides information to the fragment that all the saved state of fragment
view hierarchy has been restored.
Android Fragment Lifecycle Methods
• onStart()
• makes the fragment visible.
• onResume()
• makes the fragment interactive.
• onPause()
• is called when fragment is no longer interactive.
• onStop()
• is called when fragment is no longer visible.
• onDestroyView()
• allows the fragment to clean up resources.
• onDestroy()
• allows the fragment to do final clean up of fragment state.
• onDetach()
• It is called immediately prior to the fragment no longer being associated with its activity.
  }
}

Create Fragment Using Java

• class ExampleFragment extends Fragment


{
public ExampleFragment()
{
super(R.layout.example_fragment);
}
}
DialogFragment
• public class DialogFragment extends Fragment implements
DialogInterface.OnCancelListener, DialogInterface.OnDismissListener
PreferenceFragmentCompat
• public abstract class PreferenceFragmentCompat extends Fragment
implements PreferenceManager.OnPreferenceTreeClickListener,
PreferenceManager.OnDisplayPreferenceDialogListener,
PreferenceManager.OnNavigateToScreenListener,
DialogPreference.TargetFragment
Create Fragment Using XML
<fragment
android:id="@+id/mainImagesList"
android:name="com. Example.login"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_below="@+id/addimagebutton"
android:layout_weight="1"
android:paddingTop="55dp" />
Create Fragment Using XML
• public class FragmentA extends Fragment
{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_layout, container, false);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy