Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

what's the difference between fragment and activity in android?

user-image
Question added by Dhruvil Patel
Date Posted: 2017/02/24
Mohammad Tauqir Ansari
by Mohammad Tauqir Ansari , Senior Software Engineer , HSBC Software Developmen

Fragment is a part of an activity, which contributes its own UI to that activity. Fragment can be thought like a sub activity, whereas the complete screen with which user interacts is called as activity. An activity can contain multiple fragments. Fragment are part of an activity.

A Fragment is a section of an Activity, which has:

·        its own lifecycle

·        receives its own input events

·        can be added or removed while the Activity is running.

A fragment can't exist independently. It should be always part of an activity. A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle.

Activities are one of the fundamental building blocks of apps on the Android platform. They serve as the entry point for a user's interaction with an app and are also central to how a user navigates within an app (as with the Back button) or between apps (as with the Recents button).

Skillfully managing activities allows you to ensure that, for example:

·        Orientation changes take place smoothly without disrupting the user experience.

·        User data is not lost during activity transitions.

·        The system kills processes when it's appropriate to do so.

 

The most significant difference in lifecycle between an activity and a fragment is how one is stored in its respective back stack. An activity is placed into a back stack of activities that's managed by the system when it's stopped, by default (so that the user can navigate back to it with the Back button, as discussed in Tasks and Back Stack). However, a fragment is placed into a back stack managed by the host activity only when you explicitly request that the instance be saved by calling addToBackStack() during a transaction that removes the fragment.

Otherwise, managing the fragment lifecycle is very similar to managing the activity lifecycle. So, the same practices for managing the activity lifecycle also apply to fragments. What you also need to understand, though, is how the life of the activity affects the life of the fragment.

For more information check below:

https://developer.android.com/guide/components/activities/index.html

https://developer.android.com/guide/components/fragments.html

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.