Fragments in Android Developement
What are Fragments?
They’re basically mini activities, and an activity is usually comprised of several modular fragments.
Why would we use Fragments?
- To accommodate larger screens
- Make appearance changes during runtime, while preserving changes in back stacks managed by the activity
- Reuse different functions of the app
- Makes the application more modular, helping developers make on the fly changes
How do you make a Fragment?
1. Create a class that extends Fragment, for example if the class name is PictureDisplayFragment then it would be the following:
public class PictureDisplayFragment extends Fragment {
2. Create a view/xml file that corresponds to that fragment (this is optional, some fragments may not have a view)
3. Connect the XML fragments with the fragment java classes using onCreateView method, use the following:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container, false);
}
4. Give the elements in the fragments actions in the onActivityCreated method, use the following:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
5. Within the onActivityCreated method connect the fragment UI elements to the Java objects that will activate it
Since the elements are ultimately sitting in the activity use getActivity() to find the elements, for example if you’re activating a button called search in the fragment view/xml file then you’ll use the following:
button = (Button)getActivity().findViewById(R.id.search);
6. Go into the Activity XML file the fragment corresponds to and add the refrenece to the fragment XML file
This is easily done if you drag and drop <fragment> in the design tab, once you drop it you’ll need to specify which fragment you’re referring to.
If you were to write it out in XML then you would enter something similar to the below example:
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.mabel.fragmentcommunicationdesign.FragA"
android:id="@+id/fragA"
android:layout_marginBottom="35dp"
/>
*android:name is java package where the fragment resides