Fragment View? Who needs it!

Shayaan Siddiqui
4 min readJul 31, 2020

Background information about Fragment View

Conventional Android Development would have you think that an Activity represents a “screen” to the customer. However trying to manage activities that share configurations of a “screen” would be cumbersome and difficult. This is why a keep developer would want to use Fragments. It’s reusable code that allows you to setup your widgets that can be reused by multiple Activities. Unlike an Activity, a fragments lifecycle relies on the host lifecycle; if the user suspends the activity, all the dependent fragments are also suspended. In addition, as an added benefit, all fragments work independently of each other. This implies that if you press the ‘back button’, you can reverse a fragment transaction.

Fragment vs Activity

Although a developer can design and develop an application without ever using Fragments, depending on the app, the developer will need to perform a lot more work. Using a Fragment would allow the user to create smaller components for a larger app and would allow the reuse of these components as needed. This would eliminate recreating the same User Interface in each Activity.

Fragment Lifecycle

Below are the methods of fragment lifecycle.

  1. onAttach() :This method will be called first, even before onCreate(), letting us know that your fragment has been attached to an activity. You are passed the Activity that will host your fragment
  2. onCreateView() : The system calls this callback when it’s time for the fragment to draw its UI for the first time. To draw a UI for the fragment, a View component must be returned from this method which is the root of the fragment’s layout. We can return null if the fragment does not provide a UI
  3. onViewCreated() : This will be called after onCreateView(). This is particularly useful when inheriting the onCreateView() implementation but we need to configure the resulting views, such as with a ListFragment and when to set up an adapter
  4. onActivityCreated() :This will be called after onCreate() and onCreateView(), to indicate that the activity’s onCreate() has completed. If there is something that’s needed to be initialised in the fragment that depends upon the activity’s onCreate() having completed its work then onActivityCreated() can be used for that initialisation work
  5. onStart() : The onStart() method is called once the fragment gets visible
  6. onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session
  7. onStop() : Fragment going to be stopped by calling onStop()
  8. onDestroyView() : It’s called before onDestroy(). This is the counterpart to onCreateView() where we set up the UI. If there are things that are needed to be cleaned up specific to the UI, then that logic can be put up in onDestroyView()
  9. onDestroy() : onDestroy() called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.
  10. onDetach() : It’s called after onDestroy(), to notify that the fragment has been disassociated from its hosting activity

The Implementation (For Developers)

In the following code, we will are going to create a fictitious app called “Sneakers”. This app will show a list of sneakers and tapping any of the items will display details about the shoe.

The first step will be to create the detail page. In Android Studio, find the following location app->src->main->res->layout. (In Project layout) or
app->res->layout (In Android layout)

Right click the layout directory and click New -> Layout Resource File and type fragment_sneakers_details.xml (leave all values as their default).

The next step will be to create the accompanying kotlin file. Please Right click on com.example.appname and select New->Kotlin File/Class and type SneakersDetailFragment.kt.

class SneakersDetailsFragment : Fragment() {      
companion object {
fun newInstance(): SneakersDetailsFragment {
return SneakersDetailsFragment()
}
}

override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_sneakers_details, container, false)
}
}

This code does the following.

  1. We declare the SneakersDetailFragment as a subclass of Fragment. Thus we inherit all its properties and methods, etc.
  2. We provide a method for creating new instances of our fragment
  3. Create the view for the fragment.
    The onCreateView(), in the first argument, we call LayoutInflater.inflate to create the hierarchy of the SneakerDetailsFragment.
    On the second argument, we indicate the parent view that will hold the fragments view hierarchy.
    The third parameter will usually be set to false so that touch events aren’t passed up to the parent.

Adding a Fragment To Your View

  1. Open activity_main.xml and switch to XML view.
  2. Inside of the root ConstaintLayout, add the following code
<androidx.fragment.app.FragmentContainerView
android: id=“@+id/details_fragment”
android:layout_width=“match_parent”
android:layout_height=“match_parent”/>

The code above, adds a fragment inside your activity.
The id will tell your FragmentManager the name of the container which will host the fragment within the Activity

private fun swapFragments(
fragment: Fragment) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit()

}

The code above will do all the heavy lifting for you. This function accepts a fragment as a parameter.
The FragmentManager will begin the replacement of the existing fragment with the new one. Once it’s ready, it will commit the change. To the End User, the swap will be instant!

--

--

Shayaan Siddiqui
0 Followers

Tech Enthusiast and Software Engineer