Android Working with Fragments Part Two

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

In this post, I will be describe working with fragments using a Container layout i.e having a container, and replacing the fragments in the container according to user actions. In brief, we will have one fragment in the container at a time when user clicks on the button we replace the current fragment with the required fragment.

So,Let’s Start:-

  1. First we will create a Fragment layout containing textview and Fragment to recieve the argument and set to Textview.
  2. Then we will create another Fragment using the same layout as to describe we can use the Required Fragment.
  3. Then we will create a Activity layout containing FrameLayout which will act as a Container and four buttons on which click we will replace the fragments in the container.

Fragment layout as fragment_container.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">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="40px"
            android:text="FirstFragment"
            android:layout_centerInParent="true"
            android:id="@+id/titlename"/>
    
</RelativeLayout>

ContainerFragment

package com.coderzpassion.fragmentssample;

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.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * Created by coderzpassion on 13/06/16.
 */
public class ContainerFragment extends Fragment {

    String maintitle="";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        maintitle=getArguments().getString("title");
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_container, container, false);

        TextView title=(TextView)view.findViewById(R.id.titlename);
        title.setText(maintitle);

        return view;

    }
}

ContainerTwoFragment

package com.coderzpassion.fragmentssample;

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;

/**
 * Created by coderzpassion on 21/06/16.
 */

public class ContainerTwoFragment extends Fragment {

    String maintitle="";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        maintitle=getArguments().getString("title");
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_container, container, false);

        TextView title=(TextView)view.findViewById(R.id.titlename);
        title.setText(maintitle);

        return view;

    }
}

Activity layout as activity_container

<?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" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:layout_alignParentBottom="true"
        android:weightSum="4">

        <Button
            android:id="@+id/first"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="First"/>

        <Button
            android:id="@+id/second"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Second"/>

        <Button
            android:id="@+id/third"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="third"/>

        <Button
            android:id="@+id/fourth"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Fourth"/>

    </LinearLayout>

</RelativeLayout>

FragmentContainerActivity

package com.coderzpassion.fragmentssample;

import android.app.Activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;

/**
 * Created by coderzpassion on 13/06/16.
 */
public class FragmentContainerActivity extends FragmentActivity implements View.OnClickListener{


    Button first,second,third,fourth;
    Fragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_container);
        first=(Button)findViewById(R.id.first);
        second=(Button)findViewById(R.id.second);
        third=(Button)findViewById(R.id.third);
        fourth=(Button)findViewById(R.id.fourth);
        first.setOnClickListener(this);
        second.setOnClickListener(this);
        third.setOnClickListener(this);
        fourth.setOnClickListener(this);

        //this fragment will be called first when application runs
        ContainerFragment fragment1=new ContainerFragment();
        Bundle b=new Bundle();
        b.putString("title", "Welcome To Fragment Tutorials! CoderzPassion Click on Buttons To Replace Current fragment in Container");
        fragment1.setArguments(b);
        if (fragment1 != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment1).commit();
        }

    }


    //on click of buttons
    @Override
    public void onClick(View v) {

        switch (v.getId())
        {

          case  R.id.first:
              fragment=new ContainerFragment();
              Bundle b=new Bundle();
              b.putString("title","first");
              fragment.setArguments(b);
            if (fragment != null) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit();
            }
            break;

            case  R.id.second:
                fragment=new ContainerFragment();
                Bundle b1=new Bundle();
                b1.putString("title","second");
                fragment.setArguments(b1);
                if (fragment != null) {
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, fragment).commit();
                }
                break;

            case  R.id.third:
                fragment=new ContainerTwoFragment();
                Bundle b2=new Bundle();
                b2.putString("title","third");
                fragment.setArguments(b2);

                if (fragment != null) {
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, fragment).commit();
                }
                break;

            case  R.id.fourth:
                fragment=new ContainerTwoFragment();
                Bundle b3=new Bundle();
                b3.putString("title","fourth");
                fragment.setArguments(b3);

                if (fragment != null) {
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, fragment).commit();
                }
                break;
        }
    }
}

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=".FragmentContainerActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Output

androidfragmentsusingcontainer   androidaddingfragmentstocontainer   androidreplacingthefragmentincontainer