Fragments Flashcards
What is Fragment in Android?
A Fragment represents a reusable portion of your app’s UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own–they must be hosted by an activity or another fragment. The fragment’s view hierarchy becomes part of, or attaches to, the host’s view hierarchy.
Describe main advantage of using Fragments
Fragments introduce modularity and reusability into your activity’s UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app’s user interface, such as a navigation drawer. Conversely, fragments are better suited to define and manage the UI of a single screen or portion of a screen.
Consider an app that responds to various screen sizes. On larger screens, the app should display a static navigation drawer and a list in a grid layout. On smaller screens, the app should display a bottom navigation bar and a list in a linear layout. Managing all of these variations in the activity can be unwieldy. Separating the navigation elements from the content can make this process more manageable. The activity is then responsible for displaying the correct navigation UI while the fragment displays the list with the proper layout.
Should one fragment depend on other?
You should avoid depending on or manipulating one fragment from another. You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment. With this in mind, you should only provide a fragment with the logic necessary to manage its own UI.
Describe fragment lifecycle
- onAttach() is called when a fragment is connected to an activity.
- onCreate() is called to do initial creation of the fragment.
- onCreateView() is called by Android once the Fragment should inflate a view.
- onViewCreated() is called after onCreateView() and ensures that the fragment’s root view is non-null. Any view setup should happen here. E.g., view lookups, attaching listeners.
- onActivityCreated() is called when host activity has completed its onCreate() method.
- onStart() is called once the fragment is ready to be displayed on screen.
- onResume() - Allocate “expensive” resources such as registering for location, sensor updates, etc.
- onPause() - Release “expensive” resources. Commit any changes.
- onDestroyView() is called when fragment’s view is being destroyed, but the fragment is still kept around.
- onDestroy() is called when fragment is no longer in use.
- onDetach() is called when fragment is no longer connected to the activity.
The most common ones to override are onCreateView which is in almost every fragment to setup the inflated view, onCreate for any data initialization and onActivityCreated used for setting up things that can only take place once the Activity has been fully created.
General statements about communicating between fragments and activity
Fragments should generally only communicate with their direct parent activity. Fragments communicate through their parent activity allowing the activity to manage the inputs and outputs of data from that fragment coordinating with other fragments or activities. Think of the Activity as the controller managing all interaction with each of the fragments contained within.
A few exceptions to this are dialog fragments presented from within another fragment or nested child fragments. Both of these cases are situations where a fragment has nested child fragments and that are therefore allowed to communicate upward to their parent (which is a fragment).
The important thing to keep in mind is that fragments should not directly communicate with each other and should generally only communicate with their parent activity. Fragments should be modular, standalone and reusable components. The fragments allow their parent activity to respond to intents and callbacks in most cases.
4 ways of communicating fragment with activity
- Bundle - Activity can construct a fragment and set arguments
- Methods - Activity can call methods on a fragment instance
- Listener - Fragment can fire listener events on an activity via an interface
- ViewModel - using ViewModel for communicating and preserving data
Does Fragment need to be recreated after configuration change?
When a configuration change occurs and the activity is recreated, savedInstanceState is no longer null, and the fragment does not need to be added a second time, as the fragment is automatically restored from the savedInstanceState.
What is FragmentManager?
FragmentManager is the class responsible for performing actions on your app’s fragments, such as adding, removing, or replacing them, and adding them to the back stack.
You might never interact with FragmentManager directly if you’re using the Jetpack Navigation library, as it works with the FragmentManager on your behalf. That said, any app using fragments is using FragmentManager at some level, so it’s important to understand what it is and how it works.
How to access FragmentManager?
- getSupportFragmentManager() in activity class
- getChildFragmentManager() for managing children’s fragments and getParentFragmentManager() for host’s manager
5 lifecycle state of Fragment and how they are managed
To manage lifecycle, Fragment implements LifecycleOwner, exposing a Lifecycle object that you can access through the getLifecycle() method.
Each possible Lifecycle state is represented in the Lifecycle.State enum.
INITIALIZED CREATED STARTED RESUMED DESTROYED
Fragment’s view has a separate Lifecycle?
Yes, a fragment’s view has a separate Lifecycle that is managed independently from that of the fragment’s Lifecycle. Fragments maintain a LifecycleOwner for their view, which can be accessed using getViewLifecycleOwner() or getViewLifecycleOwnerLiveData(). Having access to the view’s Lifecycle is useful for situations where a Lifecycle-aware component should only perform work while a fragment’s view exists, such as observing LiveData that is only meant to be displayed on the screen.
What’s going on when Fragment reaches CREATED state?
When your fragment reaches the CREATED state, it has been added to a FragmentManager and the onAttach() method has already been called.
This would be the appropriate place to restore any saved state associated with the fragment itself through the fragment’s SavedStateRegistry. Note that the fragment’s view has not been created at this time, and any state associated with the fragment’s view should be restored only after the view has been created.
This transition invokes the onCreate() callback. The callback also receives a savedInstanceState Bundle argument containing any state previously saved by onSaveInstanceState(). Note that savedInstanceState has a null value the first time the fragment is created, but it is always non-null for subsequent recreations, even if you do not override onSaveInstanceState(). See Saving state with fragments for more details.
What’s going on when after Fragment reaches CREATED state?
View is being INITIALIZED.
The fragment’s view Lifecycle is created only when your Fragment provides a valid View instance. In most cases, you can use the fragment constructors that take a @LayoutId, which automatically inflates the view at the appropriate time. You can also override onCreateView() to programmatically inflate or create your fragment’s view.
If and only if your fragment’s view is instantiated with a non-null View, that View is set on the fragment and can be retrieved using getView(). The getViewLifecycleOwnerLiveData() is then updated with the newly INITIALIZED LifecycleOwner corresponding with the fragment’s view. The onViewCreated() lifecycle callback is also called at this time.
This is the appropriate place to set up the initial state of your view, to start observing LiveData instances whose callbacks update the fragment’s view, and to set up adapters on any RecyclerView or ViewPager2 instances in your fragment’s view.
What’s going on with Fragment after View was INITIALIZED?
View is being CREATED.
After the fragment’s view has been created, the previous view state, if any, is restored, and the view’s Lifecycle is then moved into the CREATED state. The view lifecycle owner also emits the ON_CREATE event to its observers. Here you should restore any additional state associated with the fragment’s view.
This transition also invokes the onViewStateRestored() callback.
Fragment and View in STARTED state
It is strongly recommended to tie Lifecycle-aware components to the STARTED state of a fragment, as this state guarantees that the fragment’s view is available, if one was created, and that it is safe to perform a FragmentTransaction on the child FragmentManager of the fragment. If the fragment’s view is non-null, the fragment’s view Lifecycle is moved to STARTED immediately after the fragment’s Lifecycle is moved to STARTED.
When the fragment becomes STARTED, the onStart() callback is invoked.