Android Tutorial

Android Tutorial Android Toast Button Widget In Android Tutorial Imageview Widget In Android Android Date Picker Example Android Time Picker Example Android Operating System Android Activity Android Architecture Android Content Providers Android Edittext Android Emulator Android Fragments Android Gridview Android Broadcast Receivers Event Handling In Android What Is Android Studio Android Navigation Drawer Android Recyclerview Android Scrollview Android Navigation Android Operating System Android ListView Android Studio Resources Android Studio's Layout Editor Android TextView Android Styles and Themes How To Show Image On An Android Application How To Insert An Email In Android Application In Android Version 8 How To Insert The Mobile Number On An Android Application Using Edittext Difference between android developer and web AdapterViewFlipper in Android with Example Android 9.0 Pie vs. Android 10, which one is better Android Development or Web Development which one is the best to choose Android Project Folder Structure Assets folder in Android How to reduce the size of APK in Android Top 7 Android App Development Books Top Programming Languages for Android Development Android Navigation Application Components Difference between android developer and web developer Event Handling in Android How to reduce the size of APK in Android Top 7 Android App Development Books Top Programming Languages for Android Development AdapterViewFlipper in Android with Example Android 9.0 “Pie” vs. Android 10, which one is better Android Development or Web Development which one is the best to choose Android EditText Android Fragments How to Update Gradle in Android Studio Navigation Drawer ScrollView What is Android Studio? Android Architecture Android Content Providers

Android Fragments

The Fragment is part of Android Jetpack. Fragments represent behaviors or parts of the user interface that can be reused in multiple activities. The fragment can be thought of as an entity that links the user interface and the behavior, and it can occupy the whole screen or a part of the activity. Fragments can be considered as portable parts of the activity, having their own life cycle, and depend on the activity of the host.

Activity is full screen, not easily reusable. Often, you want to reuse views and behaviors with multiple activities. Fragments were introduced to handle this use case. Fragments are also useful if you want your application to behave differently on different devices/orientations. This can be achieved by relocating these fragments based on the device's screen size/orientation, implementing various screen behaviors using fragments rather than activities. Fragments are a useful tool, they are lightweight compared to activities, but since they cannot exist without a host activity, it makes sense to reduce the number of activities to 1 and use fragments to implement your use cases. To improve the efficiency and compatibility of Google Android applications, google advises developers to create a multi-fragment architecture of a single activity.

Creating a Fragment

A fragment consists of two files, a layout file, and a new fragment class. The fragment class must extend the Fragment class and implement the onCreateView() function. This function populates the fragment with a desired layout. The following code segment demonstrates the layout as well as the class for a custom fragment class in Java.

fragment_new.xml

<?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=".NewFragment">


<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />


</FrameLayout>

The fragment_new.xml file is of no use until it is used to populate the fragment, which can only be done when the fragment class is created. This can be done as follows:

NewFragment.java

public class NewFragment extends Fragment {


// the fragment initialization parameters
static final String PARAM1_ARG= "par1";
static final String PARAM2_ARG= "par2";


private intPar1;
private intPar2;


public NewFragment() {
// Empty public constructor required
}


/**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @returnnew instance of fragment NewFragment.
     */


public static NewFragment newInstance(intpar1, intpar2){
NewFragment fragment = new NewFragment();
Bundle args = new Bundle();
args.putString(PARAM1_ARG, par1);
args.putString(PARAM2_ARG, par2);
fragment.setArguments(args);
return fragment;
    }


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
Par1 = getArguments().getInt(PARAM1_ARG);
Par2 = getArguments().getInt(PARAM2_ARG);
        }
    }


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

Attaching a Fragment to the Activity

A fragment can be added to an Activity in two ways i.e., statically using the XML layout and dynamically in the Activity using the Support Fragment Manager. However, the outcomeis same in both the cases. The following segment when added into the Activities XML layout attaches the fragment to the activity.

<fragment
android:name="com.example.myapplication.NewFragment"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginEnd="32dp"
android:layout_marginBottom="32dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Here, com.example.myapplication.NewFragment is the name of the Fragment class. To add a fragment dynamically, the Activity XML file should have a layout that can be used as a fragment holder. The following code segment uses FrameLayout with the if “fragment_holder” in the Activity XML file for this task.

To add a fragment dynamically within an Activity, use the code as follows:

public class MyActivityextends AppCompatActivity {
public MyActivity() {
super(R.layout.my_activity);
    }


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .setReorderingAllowed(true)
                    .add(R.id.fragment_container_view, NewFragment.class, null)
                    .commit();
        }
    }
}

The supportFragmentManager is a property of the Activity class which can be used to add, remove or replace fragments dynamically. To add a fragment, you need two arguments, the id of the Container View and an instance of the fragment class. The following codes demonstrate the functions that can be used to remove and replace a fragment.

The fragment manager maintains a stack of all the fragments added to a container. When a new fragment is added on top of another fragment, the first fragment still exists, it is just not visible on the screen. Once the topmost fragment is removed, the fragments below it remerge and are visible again. The fragment manager is a useful tool to navigate between fragments, but this can also be achieved using the navigation library by Google.