Fragments Flashcards

1
Q

What is Fragment in Android?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Describe main advantage of using Fragments

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Should one fragment depend on other?

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Describe fragment lifecycle

A
  • 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

General statements about communicating between fragments and activity

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

4 ways of communicating fragment with activity

A
  1. Bundle - Activity can construct a fragment and set arguments
  2. Methods - Activity can call methods on a fragment instance
  3. Listener - Fragment can fire listener events on an activity via an interface
  4. ViewModel - using ViewModel for communicating and preserving data
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Does Fragment need to be recreated after configuration change?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is FragmentManager?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to access FragmentManager?

A
  • getSupportFragmentManager() in activity class

- getChildFragmentManager() for managing children’s fragments and getParentFragmentManager() for host’s manager

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

5 lifecycle state of Fragment and how they are managed

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Fragment’s view has a separate Lifecycle?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What’s going on when Fragment reaches CREATED state?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What’s going on when after Fragment reaches CREATED state?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What’s going on with Fragment after View was INITIALIZED?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Fragment and View in STARTED state

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Fragment and View RESUMED state

A

When the fragment is visible, all Animator and Transition effects have finished, and the fragment is ready for user interaction. The fragment’s Lifecycle moves to the RESUMED state, and the onResume() callback is invoked.

The transition to RESUMED is the appropriate signal to indicate that the user is now able to interact with your fragment. Fragments that are not RESUMED should not manually set focus on their views or attempt to handle input method visibility.

17
Q

Fragment downward state transitions

A

When a fragment moves downward to a lower lifecycle state, the relevant Lifecycle.Event is emitted to observers by the fragment’s view Lifecycle, if instantiated, followed by the fragment’s Lifecycle. After a fragment’s lifecycle event is emitted, the fragment calls the associated lifecycle callback.

18
Q

Fragment upward state transitions

A

When moving upward through its lifecycle states, a fragment first calls the associated lifecycle callback for its new state. Once this callback is finished, the relevant Lifecycle.Event is emitted to observers by the fragment’s Lifecycle, followed by the fragment’s view Lifecycle, if it has been instantiated.

19
Q

Fragment and view STARTED in downward state transitions

A

As the user begins to leave the fragment, and while the fragment is still visible, the Lifecycles for the fragment and for its view are moved back to the STARTED state and emit the ON_PAUSE event to their observers. The fragment then invokes its onPause() callback.

20
Q

Fragment and View CREATED in downward state transitions

A

Once the fragment is no longer visible, the Lifecycles for the fragment and for its view are moved into the CREATED state and emit the ON_STOP event to their observers. This state transition is triggered not only by the parent activity or fragment being stopped, but also by the saving of state by the parent activity or fragment. This behavior guarantees that the ON_STOP event is invoked before the fragment’s state is saved. This makes the ON_STOP event the last point where it is safe to perform a FragmentTransaction on the child FragmentManager.

The ordering of the onStop() callback and the saving of the state with onSaveInstanceState() differs based on API level. For all API levels prior to API 28, onSaveInstanceState() is invoked before onStop(). For API levels 28 and higher, the calling order is reversed.

21
Q

Fragment CREATED and View DESTROYED state in downward state transitions

A

After all of the exit animations and transitions have completed, and the fragment’s view has been detached from the window, the fragment’s view Lifecycle is moved into the DESTROYED state and emits the ON_DESTROY event to its observers. The fragment then invokes its onDestroyView() callback. At this point, the fragment’s view has reached the end of its lifecycle and getViewLifecycleOwnerLiveData() returns a null value.

At this point, all references to the fragment’s view should be removed, allowing the fragment’s view to be garbage collected.

22
Q

Fragment DESTROYED state

A

If the fragment is removed, or if the FragmentManager is destroyed, the fragment’s Lifecycle is moved into the DESTROYED state and sends the ON_DESTROY event to its observers. The fragment then invokes its onDestroy() callback. At this point, the fragment has reached the end of its lifecycle.

23
Q

Why saving state with fragments is important?

A

Various Android system operations can affect the state of your fragment. To ensure the user’s state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.

24
Q

System operations that affect the state of fragment?

A
  • Added to back stack
  • Config Change
  • Process Death/Recreation
  • Removed nod added to back stack
  • Host Finished
25
Q

Various state types

A
  • Variables: local variables in the fragment.
  • View State: any data that is owned by one or more views in the fragment.
  • SavedState: data inherent to this fragment instance that should be saved in onSaveInstanceState().
  • NonConfig: data pulled from an external source, such as a server or local repository, or user-created data that is sent to a server once committed.

Oftentimes Variables are treated the same as SavedState

26
Q

Saving view state in fragments

A

Views are responsible for managing their own state. For example, when a view accepts user input, it is the view’s responsibility to save and restore that input to handle configuration changes. All Android framework-provided views have their own implementation of onSaveInstanceState() and onRestoreInstanceState(), so you don’t have to manage view state within your fragment.

Note: To ensure proper handling during configuration changes, you should implement onSaveInstanceState() and onRestoreInstanceState() for any custom views that you create.

A view needs an ID to retain its state. This ID must be unique within the fragment and its view hierarchy. Views without an ID cannot retain their state.