The standard way to declare fragments in a xml layout file is
<LinearLayout ...>
<fragment class="com.example.SomeFragment"
</LinearLayout>
where SomeFragment is a java class defined like
class SomeFragment extends Fragment {
...
}
Lets say, I have 3 fragments; fragment1, fragment2, and fragment3. When the user launches the app, I show them fragment1, and when they click on a button, I replace the fragment1 with fragment2, etc.
What is the best approach to define the 3 fragments in a single layout xml file?
I am giving an example to switch between two layouts in a fragments:
First declare a layout with two fragments:(it depends on how many fragments you want in your layout)
fragment_layout_example.xml
Above layout will display two fragments Fragment1 and Fragment2. For Fragment1 I had declared the container as content of the container is going to changed at runtime. So not declared the
Fragment
class here. for more on this checkhttp://developer.android.com/training/basics/fragments/fragment-ui.html
Then create a class FragmentExampleActivity which extends
Activity
. In case you are using Fragment in Backward compatibility mode then extendFragmentActivity
To create a layout for two fragments create two classes which extends
Fragment
Same way create Fragment class for second Fragment and set the layout
Now If you want to switch your fragment layout in Fragment1 to another layout on click of a button then create another class say Fragment3.java and set the layout you want to switch and write the below code inside the Fragment1.java
Now to come back again on the first Fragment you can click on back button. But if you want to come back on click of button then write the below code in Fragment3.java
Thanks! Hope it will help you...
You should use a FrameLayout for that, that way you don't have to specify the fragment class in the XML and that way it is not limited to one class.
and than you can set the fragment in the code like this