Fragment in Android

  • In android, fragment is a separate user interface inside the activity.
  • In other words, fragment is a part of the activity.
  • Fragment has its own life cycle and input events.
  • We can use one fragment in more than one activity.
  • When application is in running state, at this time we can add or remove the fragments.
  • We can say that fragment is like a sub activity.
  • We can see the following diagram :
  • fragment
  • The fragment concept is introduced in the Honeycomb version of android.
  • Before this concept, we can show only one activity to the user at a time. So we cannot divide the screen into the multiple parts.
  • To overcome this problem, android introduced fragment concept.
  • When fragments introduced then the user interface became more flexible because now we can display more than one interface on the activity and we can also manage fragments separately.
  • Now we can add multiple fragments in one activity to make the interface easy and it provides more options on the activity.
  • A fragment must always be embedded in activity because the life cycle of the fragment is directly affected to the life cycle of the activity.
  • For example, if we pause any activity then all the fragments present in the activity will also be pause.
  • When activity will destroy then the fragment will also be destroyed.
  • Whenever activity is in running state then we can manage all the fragments separately.
  • When we add the fragment; this is placed on the view-group of the activity hierarchy of the activity and define the view layout itself.
  • We can place the fragment in the layout file by declaring the tag.
  • Although it is not necessary to make the fragment as the part of the activity.
  • If we wish to create the fragment without user interface then we can do this. So that it will work silently.
  • Basically fragment’s concept introduced for the tablet device because it has more space than mobile phones.
  • The space of tablet can be used by these fragments so user interface became the more flexible and provide more options to the user.
  • We can change the appearance of the activity by dividing the activity into the several parts means fragments.
  • For example, we can provide the list of the links at left side fragment and when user clicks on particular link then it will be open in the right side fragment.
  • Whenever we are making the fragment then we should make a fragment which can be used in another activities means we can reuse that fragment in other activities.
  • It is necessary because we can use fragments on different screen size.
  • When we make fragments for tablets or mobile phones; then we have to configure the fragments which can run on the both devices.