Android Fragments
Android Fragments
Android Fragments
RAHUL KUMAR
ROLL NO. 1322232
Android Fragments❓🤔
Sr.
Methods Description
No.
1. onAttach( ) Called when the fragment is first attached to its host
activity. It's the first step in the fragment lifecycle.
2. onCreate( ) Initializes the fragment, similar to an activity's
onCreate(). This method is used for setting up
essential components but doesn't involve the UI.
3. onCreateView( ) Called to create the fragment’s UI. The layout for the
fragment is inflated here (convert XML layout to view
objects).
4. onActivityCreated( Called when the host activity’s onCreate() method
) has completed. It indicates that the activity is fully
created.
5. onStart( ) The fragment becomes visible to the user but cannot
yet interact with the user.
6. onResume( ): The fragment is fully visible and active, and can now
interact with the user.
Android Fragment Lifecycle Methods
Sr.
Methods Description
No.
7. onPause( ) The fragment is no longer interacting with the
user, typically when the activity goes into the
background.
8. onStop( ) The fragment is no longer visible, usually
because the activity is no longer visible.
9. onDestroyView( ) Cleans up the resources related to the
fragment's view. It is called before the
fragment’s view is destroyed.
10. onDestroy( ) Cleans up any remaining resources. The
fragment is about to be destroyed.
11. onDetach( ) The fragment is detached from the activity,
completing the lifecycle. It is now no longer
associated with its host activity.
Types of Fragments
Basically, Fragments are divided into three stages as shown here:
List fragments
Fragment transaction
Types of Fragments
Useful for switching between different fragments within the same activity
Java Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_example, container, false);
}
}
Creating and Fragments
Adding Fragments to an Activity: Fragments can be added to an activity via XML.
XML Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/example_fragment"
android:name="com.example.app.ExampleFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
contact Me:
https://x.com/Rahullibraz https://www.linkedin.com/in/rahullibraz/ rahul.leox@gmail.com
Thank-You