Android Activities, Fragments, and Lifecycle Guide
# Android Activities, Fragments, and Lifecycle Guide
## 1. Activity Lifecycle
### 1.1 Lifecycle Callbacks
An Android Activity has a well-defined lifecycle controlled by various
callbacks:
- onCreate() -> Called when the activity is first created.
- onStart() -> Called when the activity becomes visible to the user.
- onResume() -> Called when the user starts interacting with the app.
- onPause() -> Called when the activity loses focus.
- onStop() -> Called when the activity is no longer visible.
- onDestroy() -> Called before the activity is destroyed.
- onRestart() -> Called when an activity is stopped and restarted
again.
### 1.2 Activity Lifecycle with Multiple Activities
Example Scenario: App with two activities (Activity A and Activity B)
1. Start App: Activity A (onCreate -> onStart -> onResume)
2. Open Activity B: Activity A (onPause), Activity B (onCreate ->
onStart -> onResume)
3. Press Back Button on B: Activity B (onDestroy), Activity A
(onRestart -> onStart -> onResume)
4. Exit App: Activity A (onPause -> onStop -> onDestroy)
## 2. Fragment Lifecycle
### 2.1 Lifecycle Callbacks
A Fragment also has a lifecycle that interacts with the activity's
lifecycle:
- onAttach() -> Fragment attached to Activity.
- onCreate() -> Called when the fragment is created.
- onCreateView() -> Creates the UI for the fragment.
- onActivityCreated() -> Called when the activity's onCreate() has
completed.
- onStart() -> Fragment becomes visible.
- onResume() -> Fragment is active.
- onPause() -> Called when fragment loses focus.
- onStop() -> Called when fragment is no longer visible.
- onDestroyView() -> View is destroyed.
- onDestroy() -> Fragment is destroyed.
- onDetach() -> Fragment detached from Activity.
### 2.2 Fragment Lifecycle with Activity
Example Scenario: Activity contains Fragment A, replaces it with
Fragment B
1. Start App: Fragment A (onAttach -> onCreate -> onCreateView ->
onStart -> onResume)
2. Replace Fragment A with B: Fragment A (onPause -> onStop ->
onDestroyView -> onDestroy -> onDetach),
Fragment B (onAttach -> onCreate -> onCreateView -> onStart ->
onResume)
3. Exit App: Fragment B (onPause -> onStop -> onDestroyView ->
onDestroy -> onDetach)
## 3. Best Practices
- Use ViewModels to retain data across configuration changes.
- Use Fragments for modular UI instead of large activities.
- Handle Configuration Changes properly using
onSaveInstanceState().