Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Fragment: A Fragment Is Like A Sub-Activity

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 21

Fragment

A fragment is like a subactivity.

Fragment

What is fragment?
AFragmentrepresents a behavior or a
portion of user interface in an Activity. You
can combine multiple fragments in a single
activity to build a multi-pane UI and reuse a
fragment in multiple activities. You can think
of a fragment as a modular section of an
activity, which has its own lifecycle, receives
its own input events, and which you can add
or remove while the activity is running (sort
of like a "sub activity" that you can reuse in
different activities).

How does a fragment work?


A fragment must always be embedded in an activity and
the fragment's lifecycle is directly affected by the host
activity's lifecycle. For example, when the activity is
paused, so are all fragments in it, and when the activity is
destroyed, so are all fragments. However, while an activity
is running (it is in theresumed lifecycle state), you can
manipulate each fragment independently, such as add or
remove them. When you perform such a fragment
transaction, you can also add it to a back stack that's
managed by the activityeach back stack entry in the
activity is a record of the fragment transaction that
occurred. The back stack allows the user to reverse a
fragment transaction (navigate backwards), by pressing
theBackbutton.

How do we use fragment in


activity?
When you add a fragment as a part of your
activity layout, it lives in aViewGroupinside the
activity's view hierarchy and the fragment defines
its own view layout. You can insert a fragment into
your activity layout by declaring the fragment in
the activity's layout file, as
a<fragment>element, or from your application
code by adding it to an existingViewGroup.
However, a fragment is not required to be a part
of the activity layout; you may also use a
fragment without its own UI as an invisible worker
for the activity.

Steps to create simple


fragment
1. create a class in package of main activity
Like FirstFragment.java
Note: Here you should extends Fragment class from package
import android.app.Fragment

2. Create layout for each fragment


Like first.xml
Here you should use relative layout
3. Add fragment class description in activity_main.xml

Like :
<fragment
android:name="com.example.fragmenttest1.FirstFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />

FirstFragment.java
import
import
import
import
import

android.app.Fragment;
android.os.Bundle;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;

public class FirstFragment extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.first, container, false);
}
}

First.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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="60dp"
android:layout_marginTop="186dp"
android:text="Button" />
</RelativeLayout>

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.fragmenttest1.FirstFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.fragmenttest1.SecondFragment"
android:id="@+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>

Creating a Fragment
To create a fragment, you must create a subclass of Fragment(or an existing subclass of it).
TheFragment class has code that looks a lot like anActivity.
It contains callback methods similar to an activity, such asonCreate(),onStart(),onPause(), and
onStop().

Usually, you should implement at least the following lifecycle methods:


onCreate()The system calls this when creating the fragment. Within your
implementation, 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 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 aViewfrom this method that is the root of your fragment's layout. You
can return null if the fragment does not provide a UI.
onPause()The system calls this method as the first indication that the user is
leaving the fragment (though it does not always mean the fragment is being
destroyed). This is usually where you should commit any changes that should
be persisted beyond the current user session (because the user might not
come back).Most applications should implement at least these three methods
for every fragment, but there are several other callback methods you should
also use to handle various stages of the fragment lifecycle.

Most applications should implement at least these three

Types of Fragment subclass


There are also a few subclasses that you might want to extend, instead of
the baseFragmentclass:

DialogFragment Displays a floating dialog. Using this class to create


a dialog is a good alternative to using the dialog helper methods in
theActivityclass, because you can incorporate a fragment dialog
into the back stack of fragments managed by the activity, allowing
the user to return to a dismissed fragment.
ListFragment Displays a list of items that are managed by an
adapter (such as aSimpleCursorAdapter), similar to ListActivity. It
provides several methods for managing a list view, such as the
onListItemClick()callback to handle click events.
PreferenceFragment Displays a hierarchy ofPreferenceobjects as a
list, similar toPreferenceActivity. This is useful when creating a
"settings" activity for your application.

Adding a user interface


A fragment is usually used as part of an activity's user interface and
contributes its own layout to the activity.
To provide a layout for a fragment, you must implement theonCreateView()
callback method, which the Android system calls when it's time for the
fragment to draw its layout. Your implementation of this method must
return aViewthat is the root of your fragment's layout.
Note:If your fragment is a subclass ofListFragment, the default
implementation returns aListViewfromonCreateView(), so you don't need
to implement it.
To return a layout fromonCreateView(), you can inflate it from a
layout resourcedefined in XML. To help you do so,onCreateView()provides
aLayoutInflaterobject.
For example, here's a subclass ofFragmentthat loads a layout from
theexample_fragment.xmlfile:
public static class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);

Theinflate()method takes three arguments:


1. The resource ID of the layout you want to inflate.
2. TheViewGroupto be the parent of the inflated layout.
Passing thecontaineris important in order for the system
to apply layout parameters to the root view of the inflated
layout, specified by the parent view in which it's going.
3. A boolean indicating whether the inflated layout should be
attached to theViewGroup(the second parameter) during
inflation. (In this case, this is false because the system is
already inserting the inflated layout into thecontainer
passing true would create a redundant view group in the
final layout.)

Adding a fragment to an activity


1. Declare the fragment inside the
activity's layout file.
2. Or, programmatically add the
fragment to an existing
ViewGroup.
. Adding a fragment without a UI

Declare the fragment inside the activity's layout


file.
Theandroid:nameattribute in the<fragment>specifies theFragmentclass to
instantiate in the layout.
When the system creates this activity layout, it instantiates each fragment specified in
the layout and calls theonCreateView()method for each one, to retrieve each
fragment's layout. The system inserts theViewreturned by the fragment directly in
place of the<fragment>element.
Note:Each fragment requires a unique identifier that the system can use to restore
the fragment if the activity is restarted (and which you can use to capture the
fragment to perform transactions, such as remove it). There are three ways to provide
an ID for a fragment:
Supply theandroid:idattribute with a unique ID.
Supply theandroid:tagattribute with a unique string.
If you provide neither of the previous two, the system uses the ID of the container view

<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />

Programmatically add the fragment to an


existingViewGroup.
At any time while your activity is running, you can add fragments to your
activity layout. You simply need to specify aViewGroupin which to place the
fragment.
To make fragment transactions in your activity (such as add, remove, or
replace a fragment), you must use APIs fromFragmentTransaction. You can
get an instance ofFragmentTransactionfrom yourActivitylike this:
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.
beginTransaction();You can then add a fragment using theadd()method,
specifying the fragment to add and the view in which to insert it. For example:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();The first argument passed toadd()is the
ViewGroupin which the fragment should be placed, specified by resource ID,
and the second parameter is the fragment to add.
Once you've made your changes withFragmentTransaction, you must call
commit()for the changes to take effect.

Adding a fragment without a UI


The examples above show how to add a fragment to your activity in
order to provide a UI. However, you can also use a fragment to provide
a background behavior for the activity without presenting additional UI.
To add a fragment without a UI, add the fragment from the activity
usingadd(Fragment, String)(supplying a unique string "tag" for the
fragment, rather than a view ID). This adds the fragment, but, because
it's not associated with a view in the activity layout, it does not receive
a call toonCreateView(). So you don't need to implement that method.
Supplying a string tag for the fragment isn't strictly for non-UI
fragmentsyou can also supply string tags to fragments that do have a
UIbut if the fragment does not have a UI, then the string tag is the
only way to identify it. If you want to get the fragment from the activity
later, you need to usefindFragmentByTag().
For an example activity that uses a fragment as a background worker,
without a UI, see the

Managing Fragments
To manage the fragments in your activity, you need to use
FragmentManager. To get it, callgetFragmentManager()from your
activity.
Some things that you can do withFragmentManagerinclude:
Get fragments that exist in the activity, withfindFragmentById()(for
fragments that provide a UI in the activity layout) orfindFragmentByTag
()(for fragments that do or don't provide a UI).
Pop fragments off the back stack, withpopBackStack()(simulating
aBackcommand by the user).
Register a listener for changes to the back stack, with
addOnBackStackChangedListener ().
For more information about these methods and others, refer to the
FragmentManagerclass documentation.
As demonstrated in the previous section, you can also use
FragmentManagerto open aFragmentTransaction, which allows you to
perform transactions, such as add and remove fragments.

Performing Fragment Transactions


A great feature about using fragments in your activity is the ability to add, remove,
replace, and perform other actions with them, in response to user interaction. Each set of
changes that you commit to the activity is called a transaction and you can perform one
using APIs inFragmentTransaction. You can also save each transaction to a back stack
managed by the activity, allowing the user to navigate backward through the fragment
changes (similar to navigating backward through activities).
You can acquire an instance ofFragmentTransactionfrom theFragmentManagerlike this:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();Each
transaction is a set of changes that you want to perform at the same time. You can set up
all the changes you want to perform for a given transaction using methods such asadd()
,remove(), andreplace(). Then, to apply the transaction to the activity, you must call
commit().
Before you callcommit(), however, you might want to calladdToBackStack(), in order to
add the transaction to a back stack of fragment transactions. This back stack is managed
by the activity and allows the user to return to the previous fragment state, by pressing
theBackbutton.

example,
here's how you can replace one fragment with another, and
preserve the previous state in the back stack:
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction =
getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this
fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();

In this example,newFragmentreplaces whatever fragment (if any) is currently in the layout


container identified by theR.id.fragment_containerID. By callingaddToBackStack(), the replace
transaction is saved to the back stack so the user can reverse the transaction and bring back the
previous fragment by pressing theBackbutton.
If you add multiple changes to the transaction (such as anotheradd()orremove()) and call
addToBackStack(), then all changes applied before you callcommit()are added to the back stack
as a single transaction and theBackbutton will reverse them all together.
The order in which you add changes to aFragmentTransactiondoesn't matter, except:
You must callcommit()last
If you're adding multiple fragments to the same container, then the order in which you add them
determines the order they appear in the view hierarchy
If you do not calladdToBackStack()when you perform a transaction that removes a fragment,
then that fragment is destroyed when the transaction is committed and the user cannot navigate
back to it. Whereas, if you do calladdToBackStack()when removing a fragment, then the
fragment isstoppedand will be resumed if the user navigates back.
Tip:For each fragment transaction, you can apply a transition animation, by callingsetTransition
()before you commit.
Callingcommit()does not perform the transaction immediately. Rather, it schedules it to run on
the activity's UI thread (the "main" thread) as soon as the thread is able to do so. If necessary,
however, you may callexecutePendingTransactions()from your UI thread to immediately execute
transactions submitted bycommit(). Doing so is usually not necessary unless the transaction is a
dependency for jobs in other threads.
Caution:You can commit a transaction usingcommit()only prior to the activitysaving its state
(when the user leaves the activity). If you attempt to commit after that point, an exception will
be thrown. This is because the state after the commit can be lost if the activity needs to be
restored. For situations in which its okay that you lose the commit, usecommitAllowingStateLoss
().

You might also like