Android Adventures - Managing Fragments |
Written by Mike James | ||||||
Thursday, 22 May 2014 | ||||||
Page 2 of 5
We need to give the Fragments just enough UI for us to see what is happening. Go each Fragment's layout and add a single TextView used to label the Fragment and a single EditText so we have some unique data for each Fragment.
The layout for Fragment1 is:
And the layout for Fragment2 is identical apart from changing the 1 to a 2 and yes you can do this using copy and paste into the XML file. Now the final step. Move back to the main layout and use the editor to drop a Fragment into the first container. Select the container and then select the <fragment> item in the toolbox. When you select <fragment> from the Custom section of the toolbox you are offered a choice of Fragments to insert - select BlankFragment1.
When Android studio asks what it should use for the layout of the Fragment select the fragment_blank_fragment1.
If by any chance you have created the Fragment outside of the container simply drag it into the container. Repeat the task with Fragment2 and play around with the layout until you are happy.
The layout file can be seen below but yours could be slightly different - all that matters is that we have the two Fragments on display within their containers:
That's all we have to do to get the app working - apart from one code change. The project generator currently assume that you want to use the support library even though we opted not to use it. To allow the Fragments to work correctly you have to edit the MainActivity file imports to change:
to read:
and change
to
Now you can run your project and you should select a Nexus 4 to run it on because this has a normal size screen.
At this point you can see that there is plenty of room for both Fragments even on a normal screen but for the sake of a simple example let's suppose that this layout is unacceptable because both Fragments really need the entire screen to display. If you experiment a little you will also discover that the data in the Fragments is persisted - try rotating the device after putting something into one of the input fields. |
||||||
Last Updated ( Saturday, 25 July 2015 ) |