An Android Studio Java Fragment Example

As outlined in the previous chapter, fragments provide a convenient mechanism for creating reusable modules of application functionality consisting of both sections of a user interface and the corresponding behavior. Once created, fragments can be embedded within activities.

Having explored the general theory of fragments in the previous chapter, this chapter aims to create an example Android application using Android Studio designed to demonstrate the actual steps involved in creating and using fragments and implementing communication between one fragment and another within an activity.

About the Example Fragment Application

The application created in this chapter will consist of a single activity and two fragments. The user interface for the first fragment will contain a toolbar consisting of an EditText view, a SeekBar, and a Button, all contained within a ConstraintLayout view. The second fragment will consist solely of a TextView object within a ConstraintLayout view.

The two fragments will be embedded within the main activity of the application and communication implemented such that when the button in the first fragment is pressed, the text entered into the EditText view will appear on the TextView of the second fragment using a font size dictated by the position of the SeekBar in the first fragment.

Since this application is intended to work on earlier versions of Android, we will need to use the appropriate Android support library.

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Creating the Example Project

Select the New Project option from the welcome screen and, within the resulting new project dialog, choose the Empty Views Activity template before clicking on the Next button.

Enter FragmentExample into the Name field and specify com.ebookfrenzy.fragmentexample as the package name. Before clicking the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java. Modify the project to use view binding using the steps outlined in 11.8 Migrating a Project to View Binding.

Return to the Gradle Scripts -> build.gradle.kts (Module :app) file and add the following directive to the dependencies section (keeping in mind that a more recent version of the library may now be available):

implementation 'androidx.navigation:navigation-fragment:2.5.2'Code language: Gradle (gradle)

Creating the First Fragment Layout

The next step is to create the user interface for the first fragment used within our activity.

This user interface will consist of an XML layout file and a fragment class. While these could be added manually, it is quicker to ask Android Studio to create them for us. Within the project tool window, locate the app -> java -> com.ebookfrenzy.fragmentexample entry and right-click on it. From the resulting menu, select the New -> Fragment -> Gallery… option to display the dialog shown in Figure 31-1 below:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 31-1

Select the Fragment (Blank) template before clicking the Next button. On the subsequent screen, name the fragment ToolbarFragment with a layout file named fragment_toolbar:

Figure 31-2

Load the fragment_toolbar.xml file into the layout editor using Design mode. Next, right-click on the FrameLayout entry in the Component Tree panel and select the Convert FrameLayout to ConstraintLayout menu option, accepting the default settings in the confirmation dialog. Change the id from to constraintLayout. Ensure that Autoconnect mode is enabled, then select and delete the default TextView and add Plain Text, Seekbar, and Button widgets to the layout so that their positions match those shown in Figure 31-3. Finally, change the view ids to editText1, seekBar1, and button1, respectively.

Change the text on the button to read “Change Text”, extract the text to a string resource named change_text, and remove the Name text from the EditText view. Finally, set the layout_width property of the Seekbar to match_constraint with margins set to 16dp on the left and right edges.

Use the Infer constraints toolbar button to add any missing constraints, at which point the layout should match that shown in Figure 31-3 below:

Figure 31-3

Migrating a Fragment to View Binding

As with the Empty Views Activity template, Android Studio does not enable view binding support when new fragments are added to a project. Therefore, we will need to perform this migration before moving to the next step of this tutorial. Begin by editing the ToolbarFragment.java file and importing the binding for the fragment as follows:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

import com.ebookfrenzy.fragmentexample.databinding.FragmentToolbarBinding;Code language: Java (java)

Next, locate the onCreateView() method and make the following declarations and changes (which also include adding the onDestroyView() method to ensure that the binding reference is removed when the fragment is destroyed):

.
.
private FragmentToolbarBinding binding;
 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    // return inflater.inflate(R.layout.fragment_toolbar, container, false);
    binding = FragmentToolbarBinding.inflate(inflater, container, false);
    return binding.getRoot();
}
 
@Override
public void onDestroyView() {
    super.onDestroyView();
    binding = null;
}Code language: Java (java)

Once these changes are complete, the fragment is ready to use view binding.

Adding the Second Fragment

Repeating the steps to create the toolbar fragment, add another empty fragment named TextFragment with a layout file named fragment_text. Once again, convert the FrameLayout container to a ConstraintLayout (changing the id to constraintLayout2) and remove the default TextView.

Drag a drop a TextView widget from the palette and position it in the center of the layout, using the Infer constraints button to add any missing constraints. Change the id of the TextView to textView2, the text to read “Fragment Two” and modify the textSize attribute to 24sp.

On completion, the layout should match that shown in Figure 31-4:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 31-4

Repeat the steps performed in the previous section to migrate the TextFragment class to use view binding as follows:

.
.
import com.ebookfrenzy.fragmentexample.databinding.FragmentTextBinding;
.
.
private FragmentTextBinding binding;
 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    // return inflater.inflate(R.layout.fragment_text, container, false);
    binding = FragmentTextBinding.inflate(inflater, container, false);
    return binding.getRoot();
}
 
@Override
public void onDestroyView() {
    super.onDestroyView();
    binding = null;
}Code language: Java (java)

Adding the Fragments to the Activity

The main activity for the application has associated with it an XML layout file named activity_main.xml. For this example, the fragments will be added to the activity using the <fragment> element within this file. Using the Project tool window, navigate to the app -> res -> layout section of the FragmentExample project and doubleclick on the activity_main.xml file to load it into the Android Studio Layout Editor tool.

With the Layout Editor tool in Design mode, select and delete the default TextView object from the layout and select the Common category in the palette. Drag the FragmentContainerView component from the list of views and drop it onto the layout so that it is centered horizontally and positioned such that the dashed line appears, indicating the top layout margin:

Figure 31-5

On dropping the fragment onto the layout, a dialog will appear displaying a list of Fragments available within the current project, as illustrated in Figure 31-6:

Figure 31-6

Select the ToolbarFragment entry from the list and click OK to dismiss the Fragments dialog. Once added, click the red warning button in the top right-hand corner of the layout editor to display the Problems tool window. An unknown fragments message will indicate that the Layout Editor tool needs to know which fragment to display during the preview session. Select the Unknown fragment item, then click on the Pick Layout… link in the right-hand panel as shown in Figure 31-7:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 31-7

In the resulting dialog (Figure 31-8), select the fragment_toolbar entry and then click OK:

Figure 31-8

With the fragment selected, change the layout_width property to match_constraint so that it occupies the full width of the screen. Click and drag another FragmentContainerView entry from the palette and position it so that it is centered horizontally and located beneath the bottom edge of the first fragment. When prompted, select the TextFragment entry from the fragment dialog before clicking OK. Display the Problems tool window and repeat the previous steps, this time selecting the fragment_text layout. Use the Infer constraints button to establish any missing layout constraints.

Note that the fragments are now visible in the layout, as demonstrated in Figure 31-9:

Figure 31-9

Before proceeding to the next step, select the TextFragment instance in the layout and, within the Attributes tool window, change the ID of the fragment to text_fragment.

Making the Toolbar Fragment Talk to the Activity

When the user touches the button in the toolbar fragment, the fragment class will need to extract the text from the EditText view and the current value of the SeekBar and send them to the text fragment. As outlined in “An Introduction to Android Fragments”, fragments should not communicate with each other directly, instead using the activity in which they are embedded as an intermediary.

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

The first step in this process is ensuring that the toolbar fragment responds to the clicked button. We also need to implement some code to keep track of the value of the SeekBar view. For this example, we will implement these listeners within the ToolbarFragment class. Select the ToolbarFragment.java file and modify it so that it reads as shown in the following listing:

package com.ebookfrenzy.fragmentexample;
.
.
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.content.Context;
import android.widget.SeekBar;
 
public class ToolbarFragment extends Fragment implements 
                                 SeekBar.OnSeekBarChangeListener {
 
    private static int seekvalue = 10;
.
.
@Override
    public void onViewCreated(@NonNull View view, 
                   @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
 
        binding.seekBar1.setOnSeekBarChangeListener(this);
        binding.button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                buttonClicked(v);
            }
        });
    }
 
    public void buttonClicked (View view) {
 
    }
 
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {
        seekvalue = progress;
    }
 
    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
 
    }
 
    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
 
    }
}Code language: Java (java)

Before moving on, we need to take some time to explain the above code changes. First, the class is declared as implementing the OnSeekBarChangeListener interface. This is because the user interface contains a SeekBar instance, and the fragment needs to receive notifications when the user slides the bar to change the font size. Implementation of the OnSeekBarChangeListener interface requires that the onProgressChanged(), onStartTrackingTouch(), and onStopTrackingTouch() methods be implemented. These methods have been implemented, but only the onProgressChanged() method is required to perform a task, in this case, storing the new value in a variable named seekvalue, which was declared at the start of the class. Also declared is a variable to store a reference to the EditText object.

The onViewCreated() method has been added to set up an onClickListener on the button, which is configured to call a method named buttonClicked() when a click event is detected. This method is also then implemented, though it does not do anything at this point.

The next phase of this process is to set up the listener that will allow the fragment to call the activity when the button is clicked. This follows the mechanism outlined in the previous chapter:

public class ToolbarFragment extends Fragment 
    implements SeekBar.OnSeekBarChangeListener {
 
         private static int seekvalue = 10;
         private FragmentToolbarBinding binding;
         ToolbarListener activityCallback;
              
         public interface ToolbarListener {
               public void onButtonClick(int position, String text);
         }
         
         @Override
         public void onAttach(Context context) {
               super.onAttach(context);
               try {
                   activityCallback = (ToolbarListener) context;
               } catch (ClassCastException e) {
                   throw new ClassCastException(context.toString()
                       + " must implement ToolbarListener");
               }
          }
.
.
          public void buttonClicked (View view) {
                 activityCallback.onButtonClick(seekvalue, 
                      binding.editText1.getText().toString());
          }
.
.
.
}Code language: Java (java)

The above implementation will result in a method named onButtonClick() belonging to the activity class being called when the user clicks the button. All that remains, therefore, is to declare that the activity class implements the newly created ToolbarListener interface and to implement the onButtonClick() method.

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Since the Android Support Library is being used for fragment support in earlier Android versions, the activity also needs to be changed to subclass from FragmentActivity instead of AppCompatActivity. Bringing these requirements together results in the following modified MainActivity.java file:

package com.ebookfrenzy.fragmentexample;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
 
public class MainActivity extends FragmentActivity implements ToolbarFragment.ToolbarListener {
.
.
    public void onButtonClick(int fontsize, String text) {
 
    }
}Code language: Java (java)

With the code changes as they currently stand, the toolbar fragment will detect when the user clicks the button and call a method on the activity passing through the content of the EditText field and the current setting of the SeekBar view. It is now the job of the activity to communicate with the Text Fragment and to pass along these values so that the fragment can update the TextView object accordingly.

Making the Activity Talk to the Text Fragment

As An Introduction to Java Fragments in Android Studio outlined, an activity can communicate with a fragment by obtaining a reference to the fragment class instance and then calling public methods on the object. As such, within the TextFragment class, we will now implement a public method named changeTextProperties() which takes as arguments an integer for the font size and a string for the new text to be displayed. The method will then use these values to modify the TextView object. Within the Android Studio editing panel, locate and modify the TextFragment.java file to add this new method:

package com.ebookfrenzy.fragmentexample;
.
.
 
public class TextFragment extends Fragment {
.
.
    public void changeTextProperties(int fontsize, String text)
    {
        binding.textView2.setTextSize(fontsize);
        binding.textView2.setText(text);
    }
}Code language: Java (java)

When the TextFragment fragment was placed in the activity’s layout, it was given an ID of text_fragment. Using this ID, it is now possible for the activity to obtain a reference to the fragment instance and call the changeTextProperties() method on the object. Edit the MainActivity.java file and modify the onButtonClick() method as follows:

public void onButtonClick(int fontsize, String text) {
 
   TextFragment textFragment =
    (TextFragment)
      getSupportFragmentManager().findFragmentById(R.id.text_fragment);
 
   textFragment.changeTextProperties(fontsize, text);
}Code language: Java (java)

Testing the Application

With the coding for this project now complete, the last remaining task is to run the application. When the application is launched, the main activity will start and will, in turn, create and display the two fragments. When the user touches the button in the toolbar fragment, the onButtonClick() method of the activity will be called by the toolbar fragment and passed the text from the EditText view and the current value of the SeekBar. The activity will then call the changeTextProperties() method of the second fragment, which will modify the TextView to reflect the new text and font size:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Jellyfish – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 31-10

Summary

The goal of this chapter was to work through creating an example project to demonstrate the steps involved in using fragments within an Android application. Topics covered included using the Android Support Library for compatibility with Android versions predating the introduction of fragments, including fragments within an activity layout, and implementing inter-fragment communication.


Categories ,