Introduction

FragmentManager help us to handle Android fragment trasaction between fragments.  With Android fragment transaction we mean a sequence of steps to add, replace or remove fragments. FragmentManager interacts with Fragment which are within an Activity. A fragment can be created by following ways

  • Static method
  • Dynamic method

Static Method

An Activity’s layout can include Fragments as shown below. In this case, layout is static and we can’t manage the fragment at runtime. To make layout dynamic we have to use FrameLayout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  tools:context=".MainActivity" 
  android:orientation="horizontal">

  <fragment android:id="@+id/listFragment" 
    android:name="com.example.news.ArticleListFragment"
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="2"/> 
</LinearLayout>

 

Dynamic Method

FrameLayout can handle fragments at runtime. FragmentManagercan add, replace and remove fragments at runtime. Fragments can be programmatically added to or removed from a containing View in the Activity without being defined in the Activity’s layout.  To start trasaction, get FragmentTransaction from the FragmentManager instance by calling beginTransaction( ). The method commit( ) is used to asynchronously invoke the Fragment changes on the Activity.

Above layout becomes as shown below for dynamically adding fragment.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity" >
 
 <FrameLayout android:id="@+id/listFragment"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>
   
</RelativeLayout>

 

Corresponding code for the above layout is

public class MainActivity extends Activity{
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
 
    LinkListFragment llf = new LinkListFragment();
    ft.replace(R.id.listFragment, llf);
    ft.commit();
  }
}