You are on page 1of 35

Mobile Computing

Lecture #04-B
Fragments
Previous Lecture
Android Activities
• Each time a new activity start, previous activity preserves in a stack,
and when required, popped from the stack and resumes.
• By Default, all activities are subclasses of the AppCompatActivity class
and AppCompatActivity class is a subclass of Activity.
• The first task for your activity subclass is to implement the standard
activity lifecycle callback methods (such as OnCreate()) to handle the
state changes for your activity.
• onCreate() method calls setContentView() to create the primary
layout for the activity. This pass the path of XML file.
Previous Lecture
When you create a new activity in your Project, three changes appears
• An XML file containing the layout for the new activity.
• A Java file for the new activity with a skeleton class definition and
onCreate() method. 
• An additional <activity> element in the Android manifest that
specifies the new activity
<activity android:name=".newActivity"></activity>
Previous Lecture
Intent Class
Intent is used to start Android Component such as Activity, Content Provider, Broadcast
Receiver.
Intent in = new Intent(getApplicationContext(), secondActivity.class);
startActivity(in);

Bundle Class
Bundle is a utility class that let you store a set of name-vlaue pairs. Into a Bundle object,
you can put integer, long, string, arrays etc. along with the keys to identified them.
Bundle b = new Bundle();
b.putString(“myname” anystring);
String s = b.getString(“myname”);
Previous Lecture

Main Activity Sub-Activity


Intent inten = new Intent(getApplicationContext(), myActivity.class);
Bundle bn;
Bundle bnd = new Bundle();
Intent inten = getIntent();
Bnd.putString(“mystring”, “Best Regards” //OR
bnd.putString("mystring", edt1.getText().toString()); bn = inten.getExtras();

inten.putExtras(bnd); txt1.setText(bn.getString("mystring"));

startActivity(inten);
Today’s Lecture
Fragments
Fragment’s Lifecycle
Fragment Example
Fragment Subclasses
Fragment
An Activity is an application component or fundamental building block
that provides a screen, with which users can interact in order to do
something.

Fragment represents a portion of user interface in an Activity.


A Fragment is a section of an Activity, which has:
• Its own lifecycle
• Receives its own input events
• We can be added or removed fragment while Activity is running.
Activity vs Fragment
• Activity is an application component which give user interface where
user can interect. Fragment is a part of an activity,which contibute its
own UI to that activity.
• without using fragment in Activity we can’t create multi-pane UI.but
using multiple fragments in single activity we can create multi-pane UI.
• An activity may contain 0 or multiple number of fragments. A
fragment can be reused in multiple activities, so its act like a reusable
component in activities.
• For Activity we must need to mention in Manifest but for fragment its
not required.
Fragments Possible Situations
Used to create dynamic layouts Tablet /Phone / Smart Watch
Different Screen Sizes
Allows us to create different Different Orientation(Portrait /Landscape)
layouts for different situations Different Languages (Arabic / English)
Fragments …
A Fragment is a reusable component that can be shown in multiple activities
Fragments are hosted inside an activity
Fragments have their own lifecycle (more complex than an activity’s lifecycle)
A fragment is attached to a view
It must define its own layout
It was first introduced in Android 3.0 but now it can be used in older versions
too
Fragment …
A fragment can be added to an activity using xml or
programmatically.
If you add the fragment using xml, then it is not possible to
remove the fragment at run time. if you want to add, remove or
replace fragments during Activity’s run time then you have to add
the fragment programmatically.
For performing fragment transactions such as add, remove or
replace you have to create an object FragmentTranstion class
using FragmentManager object
Fragment’s Lifecycle
Fragment’s Lifecycle … Callback Functions
onAttach()
To glue fragment to its surrounding activity i.e. fragment is attached with activity
onCreate()
When fragment is just loading i.e. initialize resources other than UI
onCreateView()
Method that must return fragment's root UI view i.e. creates view hierarchy associated with
fragment
onActivityCreated()
Called when host activity’s onCreate() function is returned
onCreatedView()
Method that indicates the enclosing activity is ready i.e. initialize all views in fragment UI
onPause()
When fragment is being left / exited
onDetach()
Just as fragment is being deleted i.e. Activity is disassociated with host activity
Fragments Properties
• A fragment has its own layout and its own behavior 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-plane 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 activity will also
be stopped.
• A fragment can implement a behavior that has no user interface component.
• Fragments were added to the Android API in Honeycomb version of Android
which API version 11.
• Fragment transaction perform three operations add, remove and replace
Fragment vs. Activity
Fragment code is similar to activity but differences do exist
No direct access to layout elements
You cannot use findViewById() method is fragment. Instead, you have to use
getActivity().findViewById()
Event handlers cannot be attached in layout file (xml). It must be done in Java
code
Information passing between fragments is not straight forward:
Fragment asks its enclosing activity for data
Fragment initialization code must be mindful of order of execution. It must be
moved to onViewCreated()
If your activity support fragment removal or replace, then you have to add the
initial fragment to the activity from the activity’s onCreat() method.
To add a fragment at run time, you must provide a container view for the
fragment in your activity’s layout file in which you can insert the fragment.
A Fragment represents a reusable portion of your app's UI. A fragment
defines and manages its own layout, has its own lifecycle, and can
handle its own input events. Fragments cannot live on their own--they
must be hosted by an activity or another fragment.
Fragments are of two types
• Static Fragment
• Dynamic Fragment
Static Fragment
Step 1: Create New Project
Step 2: Create New Fragments: Every new fragment will create an fragment.xml
and fragment.java file. There is not entry in manifest file. You can decorate
fragment.xml file according to your requirement.
Step 3: Add the fragment to your activity_main.xml as
<fragment
android:id="@+id/static_fragment1"
android:name="com.technxtcodelabs.Staticfragment"
android:layout_width="match_parent" android:layout_height="match_parent"/>
The name property of fragment will decide, which newly created fragment will
appear.
activity_main.xml
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:weightSum="2"
android:orientation="horizontal">
<fragment
android:id="@+id/fragment1"
android:name="com.imran.fragmentapp.Fragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<fragment
android:id="@+id/fragment2"
android:name="com.imran.fragmentapp.Fragment2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
Dynamic Fragments

Dynamically Fragment is created by using the FragmentManager.


The FragmentManager class and the FragmentTransaction class allow you to
add, remove and replace fragments in the layout of your activity at runtime.
Add a Fragment at Run time
• You have to call the getSupportFragmentManager() to get the FragmentManager object.
• For getting the FragmentTransation object you have to call the beginTransation() method
on the FragmentManager object.
• For add a new fragment call the add() method on FragmentTransation object.
• You can perform multiple fragment transation for the activity using the same
FragmentTransation Object.
• When you ready to make the changes, simply call the commit() method on the
FragmentTransation Object.
• If you want replace a fragment, then you have to call the replace () method instead of
add() method.
• To allow the user to navigate backward through the fragment transation you must call
the addToBackStack() before commit the FragmentTransation.
To use a fragment with an activity, you need Fragment Manager
FragmentManager fM = getFragmentManager();
FragmentTransaction fT = fM.beginTransaction();

To call a fragment
Fragment frag = new Fragment1(); // Fragment1() is newly created Fragment
fT.replace(android.R.id.content, frag);
fT.commit();
Dynamic Fragment Example
Leave the fragments.java and fragment.xml files without changes.
Write the following code in activity_main.xml and MainActivity.java

<?xml version="1.0" encoding="utf-8"?> public class MainActivity extends AppCompatActivity implements View.OnClickListener {
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" Button press1, press2;
.
android:layout_width="match_parent"
android:layout_height="match_parent"
@Override
protected void onCreate(Bundle savedInstanceState) {
android:orientation="vertical" super.onCreate(savedInstanceState);
>
setContentView(R.layout.activity_main);
press1 = findViewById(R.id.press1);
<Button press2 = findViewById(R.id.press2);
android:id="@+id/press1" press1.setOnClick(this);
android:layout_width="match_parent" press2.setOnClick(this);
android:layout_height="wrap_content" }
android:text="fragment 1"/> @Override
<Button public void onClick(View v) {
android:id="@+id/press2" FragmentManager fm = getFragmentManager();
android:layout_width="match_parent" FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
android:layout_height="wrap_content" Fragment frag;
android:text="fragment 2"/>
if(press1.getId() == v.getId()){
frag = new fragment1();
<LinearLayout ft.replace(R.id.placeholder, frag);
android:id="@+id/placeholder"
ft.commit();
android:layout_width="match_parent"
}
android:layout_height="400dp"
if(press2.getId() == v.getId()){
android:orientation="vertical"
>
frag = new fragment2();
</LinearLayout> ft.replace(R.id.placeholder, frag);
ft.commit();
</LinearLayout> }
}
}
Another Example
Adding
Fragments
in Projects
root New 
Fragment (Blank)
MainActivity.java
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
book_list.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>
Fragment1.java
public class Fragment1 extends ListFragment implements AdapterView.OnItemClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg,
Bundle bundle){
return inflater.inflate(R.layout.books_list, vg, false);
}
public void onActivityCreated(Bundle bundle){
super.onActivityCreated(bundle);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.books, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position,long id){
Fragment2 fragment = (Fragment2)
getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment2);
if(fragment==null)
Toast.makeText(getActivity(), "Null object ",Toast.LENGTH_LONG).show();
else
fragment.showData(position);
}
}
book_details.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/book_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" <TextView
android:textSize="24dp"
android:layout_centerHorizontal="true"
android:id="@+id/publisher_name"
android:text="@string/book_title" /> android:layout_width="wrap_content"
<TextView android:layout_height="wrap_content"
android:id="@+id/author_name" android:textSize="18dp"
android:layout_width="wrap_content" android:layout_below="@id/author_name"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text="@string/publisher" />
android:layout_below="@id/book_title" <ImageView
android:text="@string/author_name" /> android:id="@+id/front_page"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/publisher_name"
android:src="@drawable/book_img1" />
</RelativeLayout>
book_details.xml
Fragment2.java
public class Fragment2 extends Fragment {
private String []books;
private String []authors;
private String []publishers;
private int []drawables={R.drawable.book_img1, R.drawable.book_img2,
R.drawable.book_img3, R.drawable.book_img4, R.drawable.book_img5,
R.drawable.book_img6};
TextView title, author, publisher;
ImageView image;
public View onCreateView(LayoutInflater inf, ViewGroup vg, Bundle bundle){
return inf.inflate(R.layout.book_details, vg, false);
}
Fragment2.java ….
public void onViewCreated(View view, Bundle bundle){
super.onViewCreated(view, bundle);
books = getActivity().getResources().getStringArray(R.array.books);
authors = getActivity().getResources().getStringArray(R.array.authors);
publishers =
getActivity().getResources().getStringArray(R.array.publishers);
title = view.findViewById(R.id.book_title);
author = view.findViewById(R.id.author_name);
publisher = view.findViewById(R.id.publisher_name);
image = view.findViewById(R.id.front_page);
}
public void showData(int id){
title.setText(books[id]);
author.setText(authors[id]);
publisher.setText(publishers[id]);
image.setImageResource(drawables[id]);
}
}
strings.xml
<resources>
<string name="app_name">Fragment Application</string>
<string name="book_title">Introduction to Android</string>
<string name="author_name">James Graham</string>
<string name="publisher">Cohen and Cohen</string>
<string-array name="books">
<item>Introduction to Algorithms</item>
<item>Android App Development for Dummies</item>
<item>Android Programming Cookbook</item>
<item>Algorithmics, the Spirit of Computing</item>
<item>Design and Analysis of Algorithms</item>
<item>Data Structures and Algorithms in Java</item>
</string-array>
<string-array name="authors">
<item>Thomas H. Cormen</item>
<item>Michael Burton</item>
<item>Google Inc.</item>
<item>David Harel</item>
<item>Sohail Aslam</item>
<item>Michael T. Goodrich</item>
</string-array>
strings.xml
<string-array name="publishers">
<item>MIT Press</item>
<item>John Wiley and Sons</item>
<item>Google Inc.</item>
<item>Addison Wesley</item>
<item>VU Pakistan</item>
<item>John Wiley and Sons</item>
</string-array>

</resources>
Fragment Subclasses
1. DialogFragment
A fragment meant to be shown as a dialog box that pops up on top of the current
activity.
2. ListFragment
A fragment that shows a list of items as its main content.
3. PreferenceFragment
A fragment whose main content is meant to allow the user to change settings for
the app.

You might also like