Android Working with Fragments Part three

If you are not Familiar with Fragments please check my Android Working with Fragment post.

In my earlier post, i described how to replace the fragments in container containing one fragment at a time to check refer here Android Working with Fragments Part Two

In this post, I will describe how to add the fragments in the container than on pressing the hard Back Button restore to previous Fragment. In short, how to manage the Fragments in the container and implementing the back button pressed method of activity to push the user to restore to previous UI or previous Fragment on Back button.

So,Let’s Start:-

  1. First, we will create a Fragment layout containing two buttons and Textview, one button to add the fragment to the container, other to remove the fragment from container and Textview to show help text.
  2.  Then we will use this layout and create fragment and implement the functionality to add the fragment and for another button to remove the fragment.
  3. Then we will create an Activity layout containing Framelayout which will act as a Container .

Fragment layout as fragment_first.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:layout_height="match_parent">

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Remove Fragment from Container"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginTop="50dp"
        android:text="Click on Below Button To add another fragment to the container"/>

    <Button
        android:id="@+id/addfragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add another fragment"
        />

</LinearLayout>

Fragment as FirstFragment

package com.coderzpassion.fragmentssample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by coderzpassion on 13/06/16.
 */
public class FirstFragment extends Fragment {
    public final ScheduledExecutorService worker =
            Executors.newSingleThreadScheduledExecutor();
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_first, container, false);
        Button title=(Button)view.findViewById(R.id.addfragment);
        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirstFragment firstFragment = new FirstFragment();
              final  FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.add(R.id.frame_container,firstFragment).addToBackStack("firstfragment").commit();

          // slightly added a delay as it takes some time to add fragment to container
                // then checked for no of fragments in the container
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "Total Fragments in Container " + fragmentManager.getBackStackEntryCount(), Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                };
                worker.schedule(r, 1000, TimeUnit.MILLISECONDS);
            }
        });


        Button back=(Button)view.findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // created s static method in Actvity to remove the current fragment from Container
                ((AddingFragmentContainer)getActivity()).popSingleFragment();
            }
        });
        return view;

    }



}

Activity layout as activity_addfragment.xml

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

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Activity as AddingFragmentContainer

package com.coderzpassion.fragmentssample;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by coderzpassion on 13/06/16.
 */
public class AddingFragmentContainer extends FragmentActivity {

    FragmentManager fragmentManager;
    FragmentTransaction transaction;
  public FirstFragment firstFragment;
    public final ScheduledExecutorService worker =
            Executors.newSingleThreadScheduledExecutor();

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

         firstFragment=new FirstFragment();
        fragmentManager = getSupportFragmentManager();
        transaction=fragmentManager.beginTransaction();

          transaction.add(R.id.frame_container, firstFragment).addToBackStack("firstfragment").commit();

        // slightly added a delay as it takes some time to add fragment to container
        // then checked for no of fragments in the container
        Runnable r=new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AddingFragmentContainer.this, "Fragments in Container " + fragmentManager.getBackStackEntryCount(), Toast.LENGTH_SHORT).show();
                    }
                });

            }
        };

        worker.schedule(r, 1000, TimeUnit.MILLISECONDS);
    }


    @Override
    public void onBackPressed() {


        if(fragmentManager.getBackStackEntryCount()>0)
        {
            fragmentManager.popBackStack();
            Log.e("poping back"," Done");
        }
        else
        {
            super.onBackPressed();
        }

    }

    public void popSingleFragment()
    {
        if(fragmentManager.getBackStackEntryCount()>0)
        {
            fragmentManager.popBackStack();
            Log.e("poping back"," Done");
        }
        else
        {
            super.onBackPressed();
        }
        // slightly added a delay as it takes some time to add fragment to container
        // then checked for no of fragments in the container
        Runnable r=new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AddingFragmentContainer.this, "Fragments Remaining in Container " + fragmentManager.getBackStackEntryCount(), Toast.LENGTH_SHORT).show();
                    }
                });

            }
        };

        worker.schedule(r, 1000, TimeUnit.MILLISECONDS);

       }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzpassion.fragmentssample" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
  
        <activity android:name=".AddingFragmentContainer">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output

addingfragmentstocontainer    managingbackbuttonforfragments   removingfragmentsfromcontainer