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

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class Frgment1 : Fragment() {

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

We created a empty fragment with just a layout call

import android.os.Bundle
import android.widget.TextView

class MainActivity : AppCompatActivity() {
var fraggment1:TextView ?= null

override fun onCreate(savedInstanceState: Bundle?) {
fraggment1 = findViewById(
fraggment1!!.setOnClickListener {loadfragmet(Frgment1()) }

fun loadfragmet(fragment:Fragment)

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