A fragment is an independent Android component which can be used by an activity. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts.
A fragment runs in the context of an activity, but has its own life cycle and typically its own user interface. It is also possible to define fragments without an user interface, i.e., headless fragments.
Fragments don’t subclass the Context class. Therefore you have to use the getActivity() method to get the parent activity.
Fragments simplify the reuse of components in different layouts, e.g., you can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. This is not limited to tablets; for example, you can use fragments also to support different layout for landscape and portrait orientation on a smartphone.
As it is possible to dynamically add and remove fragments from an activity, the usage of fragments allows to design very flexible user interfaces.
The life-cycle of a fragment is connected to the life-cycle of its hosting activity.
A fragment has its own life cycle. But it is always connected to the life cycle of the activity which uses the fragment.
If an activity stops, its fragments are also stopped; if an activity is destroyed, its fragments are also destroyed.
The table below shows the flow of the various callbacks in the lifecycle of a Fragment as it is being created:
Method | Description |
---|---|
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. |
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. |
The next table shows the lifecycle methods that are called as a Fragment is being destroyed:
Method | Description |
---|---|
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. |
onDetach() | Called when the fragment is being disassociated from the activity. |
In this example i will demonstrate you how to work on static and dynamic fragments.
Let’s get start by creating a project in Eclipse IDE.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. (I kept my main activity name as MainActivity.java)
2. Create a layout file for MainActivtiy.java under res ⇒ layout folder. I named the layout file as activity_main.xml. In this layout i used two fragments for static fragments and used a FrameLayout to set dynamic fragments over it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- Static fragment for fragment one --> <fragment android:id="@+id/fragment_one" android:layout_width="fill_parent" android:layout_height="100dp" class="com.android_fragment_demo.Fragment_One" /> <!-- Static fragment for fragment two --> <fragment android:id="@+id/fragment_two" android:layout_width="fill_parent" android:layout_height="100dp" class="com.android_fragment_demo.Fragment_Two" /> <Button android:id="@+id/show_one" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show Fragment One" /> <Button android:id="@+id/show_two" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show Fragment Two" /> <Button android:id="@+id/remove_fragment" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Remove Fragment" /> <!-- Container for dynamic fragments --> <FrameLayout android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="100dp" > </FrameLayout> </LinearLayout> |
3. Now, create two more layout xml files for fragments. I am going to use two fragments so i made two layouts for fragments and named as fragment_one.xml and frgament_two.xml.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:background="#FF00" android:gravity="center" android:text="Fragment One" android:textColor="#ffffff" android:textSize="30sp" > </TextView> |
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:background="#FF00DD" android:gravity="center" android:text="Fragment Two" android:textColor="#ffffff" android:textSize="30sp" > </TextView> |
4. Now, make two java files for both fragments naming Fragment_One.java and Fragment_Two.java. In this java files just return the view(layout) that you want to show.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.android_fragment_demo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Fragment_One extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_one, container, false); return view; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.android_fragment_demo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Fragment_Two extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_two, container,false); return view; } } |
5. Finally, add the following code to your MainActivity.java. In this activity i am going to show how to replace the fragment dynamically and remove the fragments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
package com.android_fragment_demo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends ActionBarActivity implements OnClickListener { FragmentManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.show_one).setOnClickListener(this); findViewById(R.id.show_two).setOnClickListener(this); findViewById(R.id.remove_fragment).setOnClickListener(this); // FragmentManager for managing fragments manager = getSupportFragmentManager(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.show_one: // Replace fragment manager.beginTransaction() .replace(R.id.container, new Fragment_One(), "First") .commit(); break; case R.id.show_two: manager.beginTransaction() .replace(R.id.container, new Fragment_Two(), "Second") .commit(); break; case R.id.remove_fragment: // First find fragment by their tags Fragment fragment_one = manager.findFragmentByTag("First"); Fragment fragment_two = manager.findFragmentByTag("Second"); // Now check if the fragment is null or not if (fragment_one != null) { // If fragment is not null then remove that frgament manager.beginTransaction().remove(fragment_one).commit(); } if (fragment_two != null) { manager.beginTransaction().remove(fragment_two).commit(); } break; } } } |
6. Now, run the app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.