What is Fragment

A Fragment is a modular section of an activity or part of an activity.A fragment represent the behaviour or portion of user interface in a fragment activity.With the help of fragment we can display the multiple view in an activity. we can also reuse the fragment.

In my program there are two buttons when the user click the first button the fragment one is called and their background color is red. When user click on second button the fragment two is called and their background color is blue.It all done in one activity.In this way we can chage the view of MainActivtity without calling another activity.


Fragment:.

In this section i am going to show the fragment with practical example.

First open the android studio and create a project and give the name of your project like FragmentDemo.

The screenshots of the program is as follows:

Smiley face Smiley face

Drag and drop the two Button from pallet on MainActivity. Open the activity_main.xml file and code look like this


<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"
    android:orientation="vertical"
    tools:context="com.example.niitpc.myapplication.MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="display fragment1"
        android:onClick="onClickButton"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="16dp" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickButton"
        android:text="display fragment2" />
    <fragment
        android:name="com.example.niitpc.myapplication.FragmentOne"
        android:id="@+id/fragment_place"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</LinearLayout>

     

In the above code you look one extra element fragment here for this you write the whole code. This fragment is container for other fragment that you will take in further in program.

android:name="com.example.niitpc.myapplication.FragmentOne" this code is very important.The android:name property show which fragment display first when the MainActivity is run. For this you simple open the FragmentOne.xml file and copy the value of Tool:Context="com.example.niitpc.myapplication.FragmentOne" and paste here .it may be differ in your computer.


Take a new fragment for this you right click on the app folder and a pop menu display click new->Fragment->Blank Fragment. A dialog box will open you can change the Fragment Name as FragmentOne click on finish.

This will create the Blank Fragment.

Open the FragmentOne.java file and delete all the code except public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState).

Open the fragment_one.xml file and code look like this.


<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:background="#ff0000"

    tools:context="com.example.niitpc.myapplication.FragmentOne">

    

</LinearLayout>


       

You make two changes here first to change the FragmentLayout to LinearLayout and android:background="#0000ff" this code make the fragment background color red.

Take a new fragment for this you right click on the app folder and a pop menu display click new->Fragment->Blank Fragment. A dialog box will open you can change the Fragment Name as FragmentTwo click on finish.

This will create the Blank Fragment.

Open the FragmentTwo.java file and delete all the code except public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState).

Open the fragment_one.xml file and code look like this.

<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:background="#ff0000"

    tools:context="com.example.niitpc.myapplication.FragmentTwo">

    

</LinearLayout>


       

You make two changes here first to change the FragmentLayout to LinearLayout and android:background="#0000ff" this code make the fragment background color blue.


Open the MainActivity.java file and write this code.

  
package com.example.niitpc.myapplication;

import android.app.Fragment;
import android.app.FragmentManager;
import android.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 onClickButton(View v)
    {
        Fragment fragment;
        if(v==findViewById(R.id.button))
        {
            fragment=new FragmentOne();
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.fragment_place,fragment);
            ft.commit();

        }
        if(v==findViewById(R.id.button2))
        {

            fragment=new FragmentTwo();
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.fragment_place,fragment);
            ft.commit();

        }



    }
}

Explanation:

onClickButton():I have created this method to call at onClick event of Button .

Fragment fragment:here i have created the framgment object of Fragment.

if(v==findViewById(R.id.button)):This statement check the click of first button.

fragment=new FragmentOne():This statement initialized the fragment object with FragmentOne class.

FragmentManager fm=getFragmentManager():The getFragmentManager() initialized the FragmentManager fm object .

FragmentTransaction ft=fm.beginTransaction();The beginTransaction() initialized the FragmentTransaction ft object.

ft.replace(R.id.fragment_place,fragment)the replace() take two argument first is frament that you have created inside the activity_main.xml file and secend is fragment object.Here the fragment is initialized with FragmentOne so it will display the FragmentOne.

ft.commit()The commit() commit the transaction.

same code in further but only one difference the second code activate when button2 is clicked and fragment object initialized with FragmentTwo .

Fragment

What is fragment for video Click here

Smiley face                     Smiley face