how to code Fragments with different Transactions in Android

In this blog post, ill show you how to code Fragments with different Transaction in Android.

Why Fragments?

A Fragment is a piece of an application’s user interface or behavior that can be placed in an Activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-acitivity.

Following are important points about fragment:

1)- A fragment has its own layout and its own behavior with its own lifecycle callbacks.

2)- You can add or remove fragments in an activity while the activity is running.

4)- You can combine multiple fragments in a single activity to build a multi-pane UI.

5)- A fragment can be used in multiple activities.

6)- Fragment life cycle is closely related to the lifecycle of its host activity.

7)- when the activity is paused, all the fragments available in the acivity will also be stopped.

8)- A fragment can implement a behavior that has no user interface component.

9)- Fragments were added to the Android API in Honeycomb version of Android which API version 11.

for more details please visit official site. http://developer.android.com/guide/components/fragments.html

 

Step 1: Create a new project File -> Android Project. While creating a new project give activity name as MainActivity and copy paste this code.


import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity implements
        OnBackStackChangedListener {

    final String FRAGMENT_TAG = "MyFragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fm = getFragmentManager();
        fm.addOnBackStackChangedListener(this);
    }

    public void onClickAttach(View view) {
        FragmentManager fm = getFragmentManager();
        Fragment theFragment = fm.findFragmentByTag(FRAGMENT_TAG);

        if (theFragment != null) {

            FragmentTransaction ft = fm.beginTransaction();
            ft.attach(theFragment);
            ft.addToBackStack("attch");
            ft.commit();
            Toast.makeText(getApplicationContext(),
                    "Now Press, Replace One Button", Toast.LENGTH_SHORT).show();
        }
    }

    public void onClickDetach(View view) {
        FragmentManager fm = getFragmentManager();
        Fragment theFragment = fm.findFragmentByTag(FRAGMENT_TAG);

        if (theFragment != null) {

            FragmentTransaction ft = fm.beginTransaction();
            ft.detach(theFragment);
            ft.addToBackStack("detach");
            ft.commit();
            Toast.makeText(getApplicationContext(), "Now Press, Attach Button",
                    Toast.LENGTH_SHORT).show();
        }
    }

    public void onClickAddOne(View view) {
        FragmentManager fm = getFragmentManager();
        FragmentOne fOne = new FragmentOne();

        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.group_container, fOne, FRAGMENT_TAG);
        ft.addToBackStack("add");
        ft.commit();
        Toast.makeText(getApplicationContext(),
                "Now Press, Remove One and Add Two Button", Toast.LENGTH_SHORT)
                .show();
    }

    public void onClickRemoveOneAddTwo(View view) {
        FragmentManager fm = getFragmentManager();
        Fragment oldFragment = fm.findFragmentByTag(FRAGMENT_TAG);

        FragmentTransaction ft = fm.beginTransaction();
        if (oldFragment != null)
            ft.remove(oldFragment);
        FragmentTwo fTwo = new FragmentTwo();
        ft.add(R.id.group_container, fTwo, FRAGMENT_TAG);
        ft.addToBackStack("remove");
        ft.commit();
        Toast.makeText(getApplicationContext(), "Now Press, Detach Button",
                Toast.LENGTH_SHORT).show();

    }

    public void onClicReplaceOne(View view) {
        FragmentManager fm = getFragmentManager();
        FragmentOne fOne = new FragmentOne();

        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.group_container, fOne, FRAGMENT_TAG);
        ft.addToBackStack("replace");
        ft.commit();
        Toast.makeText(
                getApplicationContext(),
                "Now Press, Move Previous Button and notice its shows the same order in reverse mode",
                Toast.LENGTH_SHORT).show();
    }

    public void onClickMovePrev(View view) {
        FragmentManager fm = getFragmentManager();
        fm.popBackStack();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackStackChanged() {
        // TODO Auto-generated method stub

        FragmentManager fm = getFragmentManager();
        int backstackentrycount = fm.getBackStackEntryCount();
        for (int i = 0; i < backstackentrycount; i++) {
            Log.d("MainActivity", String.valueOf(fm.getBackStackEntryAt(i)));
        }

    }
}

Step 2: Create a new class, FragmentOne.java and copy paste this code.


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

public class FragmentOne extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /**
         * Inflate the layout for this fragment
         */
        return inflater.inflate(R.layout.fragment_one, container, false);
    }

}

Step 3: Create a new class, FragmentTwo.java and copy paste this code.


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

public class FragmentTwo extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /**
         * Inflate the layout for this fragment
         */
        return inflater.inflate(R.layout.fragment_two, container, false);
    }
}

 

Step 4: Open your activity_main.xml and copy paste this code:


<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.skholingua.android.fragmenttransactions.MainActivity" >

    <LinearLayout
        android:id="@+id/group_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2" >

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickAddOne"
                android:text="Add 1" />

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickRemoveOneAddTwo"
                android:text="Remove 1 and Add 2" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2" >

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickDetach"
                android:text="Detach" />

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickAttach"
                android:text="Attach" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2" >

            <Button
                android:id="@+id/button5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClicReplaceOne"
                android:text="Replace 1" />

            <Button
                android:id="@+id/button6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickMovePrev"
                android:text="Move Prev" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/group_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/group_btn"
        android:layout_centerHorizontal="true"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

Step 5: Create a new layout xml,  fragment_one.xml and copy paste this code:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="@dimen/activity_vertical_margin"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="Fragment One"
        android:textColor="#000000"
        android:background="#26ce61"
        android:textSize="20px" />

</RelativeLayout>

Step 6: Create a new layout xml, fragment_two.xml and copy paste this code:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="@dimen/activity_vertical_margin" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:background="#26ce61"
        android:gravity="center"
        android:text="Fragment Two"
        android:textColor="#000000"
        android:textSize="20px" />

</RelativeLayout>

Step 7: Open your AndroidManifest.xml and copy paste this code:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.skholingua.android.fragmenttransactions"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>


Tips to Remember always:

1)

final String FRAGMENT_TAG = "MyFragment";

is used to finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction. This first searches through fragments that are currently added to the manager’s activity; if no such fragment is found, then all fragments currently on the back stack are searched.

2)When ever a beginTransaction() is implemented, commit() is need to be called to commit the changes to the fragment transaction.

3)addToBackStack(String) is used to add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.

ScreenShots:

Screenshot_2015-02-12-19-43-06 Screenshot_2015-02-12-19-43-10 Screenshot_2015-02-12-19-43-13 Screenshot_2015-02-12-19-43-17 Screenshot_2015-02-12-19-43-20


Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.
Download Source Code from here.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi

Leave a Reply

Your email address will not be published. Required fields are marked *