How much do you know about the life cycle of Fragment?

Fragment life cycle

Fragment is a component used to build user interfaces in Android.

Fragment has its own life cycle, including the following stages:

  1. onAttach(): Called when a Fragment is associated with an Activity. You can obtain a reference to the associated Activity through this method.

  2. onCreate(): Called when a Fragment is created, it can perform some initialization operations, such as setting layout, obtaining parameters, etc.

  3. onCreateView(): Create the user interface of Fragment. You can use this method to return a View object as the layout of Fragment.

  4. onActivityCreated(): Called when the onCreate() method of the Activity associated with the Fragment is completed. You can interact with the Activity in this method.

  5. onStart(): Called when the Fragment is visible. You can start performing some asynchronous operations or register a listener in this method.

  6. onResume(): Called when the Fragment gains focus and can interact with the user. You can start updating the UI or register a broadcast receiver in this method.

  7. onPause(): Called when a Fragment loses focus or is covered by other Fragments. You can pause UI updates or unregister broadcast receivers in this method.

  8. onStop(): Called when the Fragment is no longer visible. You can stop asynchronous operations or release resources in this method.

  9. onDestroyView(): Called when the Fragment’s view is removed. You can clean up resources or cancel asynchronous operations in this method.

  10. onDestroy(): Called when the Fragment is destroyed, the final resource release can be performed in this method.

  11. onDetach(): Called when the Fragment is disassociated from the Activity. You can clean up references related to the Activity in this method.

The above is the life cycle of Fragment. By rewriting these methods, corresponding operations can be performed at different life cycle stages.

Fragment communicates with Activity

  1. Use interface (Interface): define an interface in Fragment, and then implement the interface in Activity. Fragment can communicate with Activity by calling methods in the interface.

  2. Using Broadcast: Fragment can send broadcasts, and Activity can register a broadcast receiver to receive broadcast messages sent by Fragment.

  3. Use callback: Define a callback interface in Fragment, and then implement the interface in Activity. Fragment can communicate with Activity by calling methods in the callback interface.

  4. Use ViewModel: Use ViewModel from Android Architecture Components to share data. Fragment and Activity can communicate by observing the LiveData object in ViewModel.

  5. Using EventBus: EventBus is an open source event bus library that can be used for event communication between Fragment and Activity.

The above are several commonly used communication methods between Fragment and Activity. Developers can choose the appropriate method for communication according to specific needs.

Examples of communication between Fragment and Activity through interfaces are as follows:

  1. Define an interface in Fragment to define communication methods. For example:
public interface OnFragmentInteractionListener {
    void onFragmentInteraction(String data);
}
  1. Create a member variable in Fragment to save the instance of the interface. For example:
private OnFragmentInteractionListener mListener;
  1. In the Fragment’s onAttach() method, convert the Activity into an instance of the interface and assign it to the member variable. For example:
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                 + "must implement OnFragmentInteractionListener");
    }
}
  1. Where communication is required in the Fragment, call the interface method. For example:
mListener.onFragmentInteraction("Hello, Activity!");
  1. Implement the interface in Activity and override the interface methods. For example:
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener {
    // ...

    @Override
    public void onFragmentInteraction(String data) {
        // Process data from Fragment
    }
}

When Fragment needs to pass data to Activity, it calls the method of the interface; when Activity needs to pass data to Fragment, it can be achieved through Fragment’s public method or by directly accessing Fragment’s member variables.

The meaning of Fragment life cycle

The significance of the Fragment life cycle is to control the creation, destruction and state changes of Fragment in order to perform corresponding operations and logic at different stages. By overriding the Fragment life cycle method, we can perform corresponding operations in different life cycle stages, such as initializing data, updating UI, saving state, releasing resources, etc. This can better manage the life cycle of Fragment and improve application performance and user experience.

Note: In the life cycle of Fragment, onCreateView(), onActivityCreated(), onStart(), onResume() code>These four methods correspond to the life cycle of Activity, and you can interact with Activity in these methods.

Association between Fragment and Activity

Fragment and Activity are closely related. Fragment is a modular UI component that can be embedded in an Activity. It can host multiple Fragments in one Activity and can be shared between different Activities.

The relationship between Fragment and Activity can be achieved in the following ways:

  1. Use FragmentManager to add Fragments to Activity. Fragments can be added to the Activity layout by calling methods of FragmentManager, such as beginTransaction(), add(), replace(), etc.

  2. Use FragmentTransaction to manage the life cycle of Fragment. FragmentTransaction is an internal class of FragmentManager, which can be used to manage the addition, removal, replacement and other operations of Fragment, as well as control the life cycle of Fragment.

  3. Use Fragment’s life cycle callback method. Fragment has its own life cycle callback methods, such as onCreate(), onStart(), onResume(), etc., and you can perform Activity-related operations in these methods.

  4. Use the communication mechanism between Fragment and Activity. Fragment can communicate with Activity through interface callbacks, broadcasts, event buses, etc., thereby realizing interaction between the two.

The relationship between Fragment and Activity is managed through FragmentManager and FragmentTransaction, and the interaction between the two can also be achieved through Fragment’s life cycle callback method and communication mechanism.

Android learning notes

Android performance optimization: https://qr18.cn/FVlo89
The underlying principles of Android Framework: https://qr18.cn/AQpN4J
Android car version: https://qr18.cn/F05ZCM
Android reverse security study notes: https://qr18.cn/CQ5TcL
Android audio and video: https://qr18.cn/Ei3VPD
Jetpack family bucket article (including Compose): https://qr18.cn/A0gajp
OkHttp source code analysis notes: https://qr18.cn/Cw0pBD
Kotlin article: https://qr18.cn/CdjtAF
Gradle article: https://qr18.cn/DzrmMB
Flutter article: https://qr18.cn/DIvKma
Eight major bodies of Android knowledge: https://qr18.cn/CyxarU
Android core notes: https://qr21.cn/CaZQLo
Android interview questions from previous years: https://qr18.cn/CKV8OZ
The latest Android interview question set in 2023: https://qr18.cn/CgxrRy
Interview questions for Android vehicle development positions: https://qr18.cn/FTlyCJ
Audio and video interview questions: https://qr18.cn/AcV6Ap