Home  >  Android

Android FragmentManager and FragmentTransaction Example | Replace Fragment with another Fragment using Button OnClickListener

By Arvind Rai, June 09, 2015
This page will walk through the android FragmentManager and FragmentTransaction example in which we will replace Fragment with another Fragment using Button OnClickListener. To achieve it, first we get the instance of FragmentTransaction using FragmentManager, then call replace method which will accept view container id and new fragment instance. Finally we commit the fragment transaction.

FragmentManager

android.app.FragmentManager interacts with Fragment which are within an Activity. Find some methods of FragmentManager.

beginTransaction(): By calling this method, we start fragment transaction and returns FragmentTransaction.
findFragmentById(int id) : By passing id, it returns fragment instance.

FragmentTransaction

android.app.FragmentTransaction performs fragment operations. Find some methods.

add(int containerViewId, Fragment fragment): adds a given fragment to activity state.
attach(Fragment fragment) : The detached fragment can be re-attached by using this method.
detach(Fragment fragment) : Detaches the given fragment from UI. Fragment state is still managed by FragmentManager.
remove(Fragment fragment) : Removes the given fragment from UI and container.
replace(int containerViewId, Fragment fragment) : For the given container view id, we can replace existing fragment by new given fragment.
commit(): Transaction is committed.

View.OnClickListener

android.view.View.OnClickListener is an interface which has onClick(View v) method. OnClickListener is implemented to listen click event on UI component. Suppose we have a button on our UI, we can implement on click listener for it and register by calling button.setOnClickListener(listener).

Demo Project Structure in Eclipse

Android FragmentManager and FragmentTransaction Example | Replace Fragment with another Fragment using Button OnClickListener

Layout XMLs


main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_label1"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_label2"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.concretepage.android.FragmentOne"
        android:id="@+id/output"/>
</LinearLayout> 

fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:gravity="center"
    android:background="#FF0000"
    android:layout_height="match_parent">
    <TextView
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_gravity="center"
	    android:textColor="#b0b0ff"
	    android:textSize="20sp"
	    android:id="@+id/msg1"/>
</LinearLayout> 

fragment_two.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:gravity="center"
    android:background="#b0b0ff"
    android:layout_height="match_parent">
    <TextView
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_gravity="center"
	    android:textColor="#FF0000"
	    android:textSize="20sp"
	    android:id="@+id/msg2"/>
</LinearLayout> 

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Concrete Page</string>
    <string name="btn_label1"> Fragment One </string>
    <string name="btn_label2"> Fragment Two </string>
</resources> 

Activity and Fragment Implementations


FragmentOne.java
package com.concretepage.android;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.cp.android.R;
public class FragmentOne extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, viewGroup, false);
        TextView output= (TextView)view.findViewById(R.id.msg1);
        output.setText("Fragment One");
        return view;
    }
}  

FragmentTwo.java
package com.concretepage.android;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.cp.android.R;
public class FragmentTwo extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_two, viewGroup, false);
        TextView output= (TextView)view.findViewById(R.id.msg2);
        output.setText("Fragment Two");
        return view;
    }
}  

MainActivity.java
package com.concretepage.android;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.cp.android.R;
public class MainActivity extends FragmentActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        OnClickListener listener = new OnClickListener() {
		public void onClick(View view) {
			Fragment fragment = null;
			if(view == findViewById(R.id.button1)){
	                  fragment = new FragmentOne();
			} else {
	                  fragment = new FragmentTwo();					
			}
                        FragmentManager manager = getSupportFragmentManager();
                        FragmentTransaction transaction = manager.beginTransaction();
                        transaction.replace(R.id.output, fragment);
                        transaction.commit();
		}
         };
        Button btn1 = (Button)findViewById(R.id.button1);
        btn1.setOnClickListener(listener);
        Button btn2 = (Button)findViewById(R.id.button2);
        btn2.setOnClickListener(listener);
    }
} 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cp.android"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11" />
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.concretepage.android.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Output

When we run app, we will get two button in UI using which we can change fragment.
Android FragmentManager and FragmentTransaction Example | Replace Fragment with another Fragment using Button OnClickListener

Download Source Code

Download APK file

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us