What is fragment and why we use fragment?

First lets see what is fragment?

Fragment can be called as part of activity or may be ‘’sub activity’’ the fragments lifecycle depends on the activity lifecycle since the fragments are included inside the activity. It represent the reusable portion of the app UI.

Fragment Lifecycle

Lets see the lifecycle of fragment

onAttach() → It will be called for the first time when the fragment get attached to the activity.

onCreate() → It take care of initialization of fragment.

onCreateView() → Here the view will be created and returned

onActivityCreated() → It will be called at the time of activity oncreate() method gets executed.

onStart() → It will called whenever the fragment gets visible to user

onResume() → When the fragment gets interactive with user.

onPause() → When the fragment is not visible to user.

onStop() →When the fragment is no longer interactive with user

onDestroyView() → clean up fragment oriented resource

onDestroy() → we can do our final clean up

onDetach() → where fragment is no longer attached to activity

why we use fragment?

For reusable UI its good to use fragment so we can call if we need the same screen some where in activity

Example for fragment

We created a empty fragment with just a layout call

And from the MainActivity we called the fragment by loadfragmet method it will replace the current fragment

Knowledge is everything.Check out my app at

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why do you need Android App development?

Android: Custom Toolbar

Here is some of the top news you may not be aware of.

CameraX Overview & Advanced

Android Broadcast Receivers

listview vs recyclerview

Understanding Android Storage

Unit testing using Spek framework

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pandiyan Mani

Pandiyan Mani

Knowledge is everything.Check out my app at

More from Medium

Android — Text View

Nifty lil trick to create dummy objects

Quick Note: Flow’s asLiveData() with CoroutineContext parameter

Room Migrations — “Testing”