FRAGMENT IN ANDROID

A fragment is a chunk part of an Activity which is used for achieving Panel Based Designing, to achieve reusability of GUI as well as to show effective GUI(large screen).

  • It is added after Honeycomb 11.
  • It is always associated with an Activity.
  • We can use more than one fragment.
  • It has its own layout and behavior.
  • It has its own life cycle.
  • It can be added or removed at run time.
  • Multiple fragments can be combined in a single activity.
  • It can be used in multiple activities.

There are 2 types of fragment:-

  1. @android.app.Fragment
  2. @android.support.V4.Fragment

LIFECYCLE OF FRAGMENT

  1. onAttach()- attaches fragment to activity.
  2. onCreate()-Initialisation or allocation of memory
  3. onCreateView()-like setcontentView(), for providing the view
  4. onActivityCreated()- provides an Acknowledgement that our task is complete.
  5. Start
  6. Resume
  7. Pause
  8. Stop
  9. onDestroyView()- first destroy all views
  10. onDestroy()-destroy all allocated resources
  11. onDetach()-separate out fragment from an Activity.

Fragment in Android(Add,Delete and Replace) 1

SOME IMPORTANT TERMS:-

Fragmentmanager

A FragmentManager manages Fragments in Android, specifically it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments.

FragmentTransaction

FragmentTransaction gives us methods to add, replace, or remove fragments in Android. It gives us an interface for interacting with fragments.

addToBackStack(null)

The method, addToBackOfStack(String name), adds this transaction to the back stack, this can be used so that Fragments are remembered and can be used again by the Activity

Read More : Android Runtime Permissions with Dexter Library

Let’s create an application using Fragment:-

1. Create a new fragment frag1 by Right click on App>select New>select Fragment>select Fragment (Blank). It will automatically create its JAVA and corresponding XML file.

2. Create another fragment frag2 using same procedure of above

Fragment in Android(Add,Delete and Replace) 2

Fragment in Android(Add,Delete and Replace) 3

3. Open the fragment_frag1.xml and copy the below the code.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".frag1"
    android:background="@color/colorPrimary">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="fragment 1"
        android:textSize="50dp"
        android:textColor="#ffffff"
         android:gravity="center"/>

</FrameLayout>

4. Open the fragment_frag2.xml file and follow the below code. In this fragment, we have given red colour.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".frag2"
    android:background="@color/colorAccent">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="fragment 2"
        android:textColor="#ffffff"
        android:textSize="50dp"
        android:gravity="center"
        />

</FrameLayout>

5. Frag1.java 

package com.example.frag;

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

public class frag1 extends Fragment {


    public frag1() {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(LayoutInflater l, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= l.inflate(R.layout.fragment_frag1, container, false);
        return  v;
    }


}

6. frag2.java

package com.example.frag;

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

public class frag2 extends Fragment {


    public frag2() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_frag2, container, false);
        return v;
    }

}

7. This is main screen of our page, open activity_main.xml and copy the below code.

<?xml version="1.0" encoding="utf-8"?>

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="FRAGMENT TUTORIAL"
        android:textSize="30dp"
        android:textColor="@color/colorPrimary"/>

    <fragment
        android:id="@+id/f1"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        class="com.example.frag.frag2"
        android:layout_margin="30dp"/>

    <Button
        android:id="@+id/add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ADD A FRAGMENT"
        android:onClick="add"/>
    <Button
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="DELETE A FRAGMENT"
        android:onClick="delete"/>
    <Button
        android:id="@+id/replace"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="REPLACE A FRAGMENT"
        android:onClick="replace"/>

</LinearLayout>

Fragment in Android(Add,Delete and Replace) 4

8. In main activity, we will create three buttons: ADD A FRAGMENT, DELETE A FRAGMENT, REPLACE A FRAGMENT.

package com.example.frag;

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.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    public void add(View v)
    {

            FragmentManager fm=getSupportFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.add(R.id.f1,new frag1());
            Toast.makeText(this, "Fragment is added!!!!!!", Toast.LENGTH_SHORT).show();
            ft.addToBackStack(null);
            ft.commit();
    }

    public void delete(View v)
    {

        FragmentManager fm=getSupportFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        if(fm.getBackStackEntryCount()>0) {
            fm.popBackStack();
            Toast.makeText(this, "Fragment is deleted!!!!!!", Toast.LENGTH_SHORT).show();
        }

        ft.commit();
    }

    public void replace(View v)
    {

        FragmentManager fm=getSupportFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        ft.replace(R.id.f1,new frag2());
        Toast.makeText(this, "Fragment is replaced!!!!!!", Toast.LENGTH_SHORT).show();
        ft.addToBackStack(null);
        ft.commit();
    }


}

THREE FRAGMENT IN ANDROID

1. TO ADD A FRAGMENT

public void add(View v)
    {

            FragmentManager fm=getSupportFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.add(R.id.f1,new frag1());
            Toast.makeText(this, "Fragment is added!!!!!!", Toast.LENGTH_SHORT).show();
            ft.addToBackStack(null);
            ft.commit();
    }

It adds a fragment frag1() to the fragment layout which has id f1. Also, add this fragment to Backstack to maintain a record of added fragments.

2. TO DELETE A FRAGMENT

public void delete(View v)
    {

        FragmentManager fm=getSupportFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        if(fm.getBackStackEntryCount()>0) {
            fm.popBackStack();
            Toast.makeText(this, "Fragment is deleted!!!!!!", Toast.LENGTH_SHORT).show();
        }

        ft.commit();
    }

It deletes one fragment which is on the top of the Stack.

3. TO REPLACE A FRAGMENT

public void replace(View v)
    {

        FragmentManager fm=getSupportFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        ft.replace(R.id.f1,new frag2());
        Toast.makeText(this, "Fragment is replaced!!!!!!", Toast.LENGTH_SHORT).show();
        ft.addToBackStack(null);
        ft.commit();
    }

It replaces one fragement to another like fragment 2 is replaced with fragment which is already placed on the layout of id f1.

This was a simple tutorial on how to add , delete and replace fragments in an Android Application.

You can access full code on github by clicking on the below link and For any Query, Comment down below

DOWNLOAD CODE