Modern Android App Development — 6 — Introduction to Fragments

Lukasz Madrzak (Woocassh)
4 min readMay 8, 2017

Hey guys! Welcome to the 6th tutorial in the series about android development.

Video: https://youtu.be/u7r48OLZPlQ

Today we’ll learn about Fragments. Some theory first:

A Fragment represents a behaviour or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

So basically, fragments are views which we will manage and navigate through our activity.

Let’s continue with our project.

Today we will create two fragments and navigate between them.

Go to Main Activity and clear it out first so you’re left with this:

public class MainActivity extends AppCompatActivity {


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


}
}

In order to manage our fragments we will need a FragmentManager. Let’s define this instance variable:

private FragmentManager fragmentManager;

Make sure that Android Studio imports the correct package:

import android.app.FragmentManager;

And now let’s initialize it in the onCreate:

fragmentManager = getFragmentManager();

Now — let’s create a method that will be responsible for changing the fragment for us. We will only have to feed it 2 arguments:

  1. Fragment — what fragment to we want to go to
  2. Boolean — whether we want to add this view to back stack. (If set to true, the app will go back to the previous screen.)
public void changeFragment(Fragment target, Boolean addToBackStack) {
FragmentTransaction ft = fragmentManager.beginTransaction();

ft.replace(R.id.container, target);
if (addToBackStack) {
ft.addToBackStack(target.getTag());
}
ft.commit();
}

It’s a simple method. ft.commit() — this is where the change occurs.

The app will give out at this stage because we do not have “R.id.container” defined in our view. Let’s go and do that now.

Head to activity_main.xml screen. Swap to Text mode and let’s clear it out for now. You’re now left with this:

<?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"
android:orientation="vertical"
tools:context="com.madrzak.tutorialfour.MainActivity">



</LinearLayout>

Let’s change the LinearLayout to RelativeLayout and inside it add the following:

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

This is the part that will be filled by our Fragments. And also add the the following which we’ll use as a makeshift navigation.

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">

<Button
android:id="@+id/btnFragment1"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_weight="1"
android:text="Fragment 1" />

<Button
android:id="@+id/btnFragment2"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_weight="1"
android:text="Fragment 2" />
</LinearLayout>

Now, in order to keep our code organized — we’ll keep all our fragments in one folder. Right click on your package in Android project view New > Package and call it “fragment

Now right click on that newly created folder and let’s create a Fragment!

New > Fragment > Fragment (Blank)

Name this fragment: “FirstFragment” and make sure to untick “Include fragment factory methods” and “Include interface callbacks”

This is what your newly created fragment should look like:

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

import com.madrzak.tutorialfour.R;
public class FirstFragment extends Fragment {


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


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

}

There’s something we must fix here. Specificially this line:

import android.support.v4.app.Fragment;

Must be changed to the following in order for it to work with our FragmentManager

import android.app.Fragment;

Let’s head to it’s view (“fragment_first.xml”) and edit it.

While in Design mode — select TextView and set:

  1. alignment: center
  2. textSize: 30dp
  3. text: “Our first Fragment!”

Let’s create our SecondFragment in the same way as above.

Right click on fragment folder New > Fragment > Fragment (Blank), rename and untick 2 bottom boxes. Press Finish.

Make sure you adjust the import line to same as above. (import android.app.Fragment;)

Head to it’s view (“fragment_second.xml”). And in Design mode adjust the TextView similar to as above:

  1. alignment: center
  2. textSize: 30dp
  3. text: “Our second Fragment!”

The next thing we must figure out is how to set the fragment to show up on startup on of our app, and then, how do we navigate between them by clicking respective buttons.

  1. To set the fragment on start up is actually very simple. Put the following line of code to the onCreate of our MainActivity. You can see that we are choosing FirstFragment to be the first view our users will see.
changeFragment(new FirstFragment(), false);

2. In order to navigate between the 2 fragments we must first set up our buttons and set listeners. In MainActivity:

private Button btnFragment1;
private Button btnFragment2;

In onCreate:

btnFragment1 = (Button) findViewById(R.id.btnFragment1);
btnFragment1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

}
});

btnFragment2 = (Button) findViewById(R.id.btnFragment2);
btnFragment2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

}
});

I hope that at this stage you can see what must be done next.

In the btnFragment1 button listener we will change the fragment to FirstFragment in the following way:

changeFragment(new FirstFragment(), false);

and in btnFragment2 we will change the fragment to SecondFragment like this:

changeFragment(new SecondFragment(), false);

Let’s run our app and test it out!

You can see exactly how it should behave here:https://youtu.be/u7r48OLZPlQ?t=14m30s

Congratulations! You know now about Fragment and how to navigate between them. You can play around with this and add couple more fragments in the same way as we have the first two.

--

--