Android Fragments Tutorial – Android Programming

Android Fragments Tutorial – Android Programming

Fragments in android is a pretty confusing topic to start off. It is often used along with the activity and lot of tutorials talk about how a fragment is bound to the lifecycle of the activity. We will see what a fragment is and how to create one to use it effectively.

To start off let’s know the difference between a Fragments and an Activity.

Fragment vs Activity

Think of Fragment as a small piece of a working module that can work independent to each other. That is, an Activity can contain many fragments inside it, and they can work independent to each other. A fragment is capable of having its own lifecycle (Create, attach, resume, destroy) which we will see in detail below.

An activity on the other hand, is the building block of any application. An activity can have multiple fragments inside it acting independent of the Activity and other Fragments. However, the restriction is that, a fragment is bound to the Activity. If a Activity is killed/destroyed all the fragments inside it will also be destroyed.

Lets see an example below.

Android Fragment
Fragment in Android (Image Source: Android developer)

If the image isnt clear enough. We will see an example for the Fragment in real application.

Take this application for example – Follow My Friend. The application contains a bottom Menu like below.

Screenshot Image

The Menu contains Home/Friend/Bell icons. Clicking on them, brings in a sliding page on top of each other. How does this happen?

The sliding pages on top of each other is called the Fragment. The Fragment has its own lifecycle, like above and can hold any layout. The home activity holds the bottom menu drawer and the upper portion is dynamically updated. This is how a Fragment works.

Fragment Lifecycle

We have now seen what a Fragment is and how different it is from an Activity. The next important point to consider is the Fragment lifecycle. In other words, how is a Fragment Created and Destroyed.

Fragment Lifecycle

The long image we have is confusing to start with, but on reading out every single process we get the overall picture.

The Fragment is first activated by calling the onAttach() method, which is done by a View Adapter (We will see a brief definition below). Once the onAttach is called. the Fragment is created and the view is also created.

The onActivityCreated() method inturn calls the onStart() where all our process begins to happen. onResume() follows this

Once you have switched to another Fragment, the current fragment has to be destroyed, and that’s what happens in the lower portion of the image.

 

The onPause() is called which inturns calls onStop() and onDestroyView() is called.

The Activity is given a notification that a specific Fragment is Detached from its View Adapter and the next Fragment adds from the start.

This happens every single time, a fragment is changed and attach and detached are called.

The next obvious question is. does the entire element that we had inside a Fragment also get destroyed when the Fragment is Detached?

The answer is Yes and No. If you do not do anything about storing the state of the elements that a Fragment holds then the elements will get destroyed. It is upto the developer to save the stateBundle and call it when the Fragment is re- attached.

 

Create A Fragment In Android:

Inorder to create a Fragment, we will have to extend the Class Fragment and override the Lifecycle methods we saw above to our needs.

Lets see the basic implementation.

public class ExampleFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //Return a View here
        return null;
    }
}

This is a very basic overriding of the method onCreateView(). We will be using the LayoutInflater to inflate the layout we want to show in this Fragment and then return that view.

Extending this Fragment Implementation, we will go a bit further to create our Example

 

Creating a Application with Fragment

We will now create a sample application using Fragments and see how they operate.

A very stripped down example for understanding purpose is given below

We will need two layouts.

first_fragment.xml

<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"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:text="This is First Fragment"
        android:textSize="25sp" />

</RelativeLayout>

second_fragment.xml

<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"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:text="This is Second Fragment"
        android:textSize="25sp" />

</RelativeLayout>

FirstFragment.java

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

public class FirstFragment extends Fragment {
    
    View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.first_fragment, container, false);
        return view;
    }
}

SecondFragment.java

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

public class SecondFragment extends Fragment {
    View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.second_fragment, container, false);
        return view;
    }
}

MainActivity.java

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button button;
    Boolean Toggle = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        button = (Button) findViewById(R.id.changeFragment);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Toggle == true)
                {
                    loadFragment(new FirstFragment());
                    Toggle = false;
                }
                else {
                    loadFragment(new SecondFragment());
                    Toggle = true;
                }
            }
        });
    }
    private void loadFragment(Fragment fragment) {

        FragmentManager fm = getFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout, fragment);
        fragmentTransaction.commit();
    }
}
The resulting Output is
FirstFragment
FirstFragment
SecondFragment
SecondFragment

 

Fragments – Additional Concepts

Apart from the basic fragment we saw now, there are some important Fragment types like below.

  • ListFragment
  • DialogFragment
  • PreferenceFragment
  • WebViewFragment

These Fragments have some special purpose and plays a important role in creating a complete application.

Conclusion

Check out my project here, for a better understanding of how i created a application in 3 hours.

I will be creating a another post about creating a custom Fragments and some important tricks and best practices for creating the Fragments.

Drop in any comments you have below.

“Learn and Be Curious”

Leave a Comment