When reading the reviews on one of the Android books I recommend, I came across this question:
I read the chapter on UI and the section on fragments. I followed the given example step by step and got it to work. So far so good. I then attempted to build my own solution of dynamically adding fragments to a layout. I’m none the wiser as to how to reference the views within each dynamically added fragment. The 3 things I really want to know about any control: (1) how to add statically, (2) how to add dynamically, (3) how to reference any view I place into the UI.
Fragments can be a tricky subject! I’ll break down the difference between static and dynamic fragments in this post to give you a better idea of how they work.
Add Static Fragment
Adding fragments statically via XML is the preferred method when your UI won’t vary drastically. You can use these XML fragments and leverage the resource system to build UIs that fit multiple form factors without worrying about managing the state of all the fragments in your application.
<?xml version="1.0" encoding="utf-8"?> <fragment android:id="@+id/static_fragment" android:name="com.example.myapp.YourFragmentHere" android:layout_width="match_parent" android:layout_height="match_parent"/>
Note: After you have defined it this way, don’t try to replace, delete, etc. with a FragmentTransaction!
You obtain a reference to the fragment in Java using the FragmentManager:
Fragment fragment = getFragmentManager().findFragmentById( R.id.static_fragment );
Note: If using the support library, you’ll need to call getSupportFragmentManager()
instead and will be using a FragmentActivity.
Add Dynamic Fragment
First you’ll need a holder to house your fragments. FrameLayout is a popular choice.
<FrameLayout android:id="@+id/fragment_holder" android:layout_width="match_parent" android:layout_height="match_parent"/>
To access in Java, you’ll need to get access to the FragmentManager.
FragmentManager manager = getFragmentManager();
After you have the reference, it’s time to start the transaction. You give it the id of your holder (that you defined in your XML) an instance of your fragment and a tag string to identify the fragment (I’m using the name of the class).
FragmentTransaction transaction = manager.beginTransaction(); String tag = fragment.getClass().getSimpleName(); transaction.replace( R.id.fragment_holder, new YourFragmentHere(), tag );
If you are so inclined, you can add this fragment to the backstack:
transaction.addToBackStack( tag );
After you are done configuring the transaction, tell the fragment to make the changes!
transaction.commit();
I pulled the snippets shown here from a full working example.