Skip to content

Instantly share code, notes, and snippets.

@azlanjamal
Last active December 19, 2017 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azlanjamal/aeefc25d446349b1a2fe56beaf8a8e64 to your computer and use it in GitHub Desktop.
Save azlanjamal/aeefc25d446349b1a2fe56beaf8a8e64 to your computer and use it in GitHub Desktop.
Fragment Guide
Add Fragment through XML.
1. Create a xml for the fragment.
2. Create a class for the fragment and extend android.app.Fragment(for Honeycomb/API 11 and above).
3. Link fragment class with the xml created in step 1. Link them inside onCreateView method.
return inflater.inflate(R.layout.fragment_xml_name, container, false);
4. Add fragment to activity through xml file. Open activity's xml.
<fragment
android:id="@+id/fragment_xml_a"
class="FragmentXMLA" />
Introduction to Fragment Manager and Fragment Transactions
1. Fragment Manager
- Maintains list of Fragments in the current Activity.
- Track Fragment Using ID (Assign an id to a fragment, Use findFragmentById with Fragment Manager to get that fragment).
- Track Fragment Using TAG (Assign a TAG to a fragment, Use findFragmentByTag with Fragment Manager to get that fragment).
2. Fragment Transactions
    - add - Add a fragment to the activity.
- remove - Remove an existing fragment, its view is also removed.
- replace - Remove one fragment from the activity and add another.
- hide - Hides an existing fragment, its view is hidden.
- show - Show previously hidden fragment.
 
Add Fragment through code.
1. Make an Activity.
2. Create a layout file for the Fragment in XML.
3. Create a class in Java that extends from Fragment or its subsclasses.
4. Link the layout of the Fragment with its Java file.
5. Create an object of your Fragment class in your Activity.
6. Get a reference to FragmentManager using getFragmentManager() or getSupportFragmentManager().
7. FragmentManager is reponsible for interacting with Fragments, ex: finding them.
8. Use the FragmentManager to begin a FragmentTransaction.
9. FragmentTransaction involves operations such as add, remove, replace, hide etc.
10. For example use the FragmentTransaction to Add the fragment object.
11. Commit or finish the FragmentTransaction.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment