Introduction
A Fragment is a piece of an application’s user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager
. Fragments must be embedded in activities; they cannot run independently of activities. Like an Activity, a Fragment has its own lifecycle. An Activity that hosts a Fragment can send information to that Fragment, and receive information from that Fragment.
Define Fragment
A fragment, like an activity, has an XML layout file and a class that represents the Fragment controller.
<!-- fragment_layout.xml -> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>
Code for the above fragment is given below
public class MyFragment extends Fragment { // Called when Fragment create its View object hierarchy, // either dynamically or via XML layout inflation. @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { // Defines the xml file for the fragment return inflater.inflate(R.layout.fragment_foo, parent, false); } // This event is triggered soon after onCreateView(). @Override public void onViewCreated(View view, Bundle savedInstanceState) { // Setup any handles to view objects here TextView tView = view.findViewById(R.id.textView); } }
Embed Fragment
There are two ways to add a fragment to an activity: dynamically using code and statically using XML.
Fragment Lifecycle
Fragment has many methods which can be overridden to plug into the lifecycle
- onAttach() is called when a fragment is connected to an activity.
- onCreate() is called when fragment is created.
- onCreateView() inflate the XML layout for the Fragment. As a result, the Fragment is visible in the Activity. To draw a UI for your Fragment, you must return the root View of your Fragment layout. Return null if the Fragment does not have a UI.
- onViewCreated() is called after onCreateView() and ensures that the fragment’s root view is non-null.
- 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.