You can add a fragment to the user interface at runtime with the FragmentManager. David describes how to instantiate a fragment as a Java object, and then how to add it to the UI with a fragment transaction.
- [Instructor] I previously described…how to create a fragment class…and its associated layout file…and then how to display that fragment using XML markup.…You can also display fragments dynamically using Java code.…In this exercise, I've renamed a few things.…First of all, I've renamed my Java class to fragment one…and its associated layout file to fragmentone.xml.…In my main activity class,…I've added just an addFragment method.…It's an event handler method,…so it accepts a view object.…
And in the activity, I've added a button…which is currently invisible.…It's onClick event is calling that method.…Now I'm going to be using exactly the same…basic fragment I had before.…It has a simple layout with just a text view…that's displaying a bit of text.…But instead of loading the fragment statically with XML,…I'll load it dynamically with Java.…I'll go to my main activity,…and instead of a fragment tag,…I'll use something called a frame layout.…A frame layout is designed to contain…exactly one child object.…
And it has to be a view object.…
Released
8/8/2017- Supporting different platform versions
- Setting minimum and target platforms
- Working with multiple screens
- Creating alternative resource directories, XML layout files, and bitmap resources
- Creating dynamic UIs with fragments
- Creating a project with fragments
- Controlling a fragment with Java code
Share this video
Embed this video
Video: Add a fragment with a transaction