mushmuch
mushmuch

Reputation: 1

Why should I not add Fragments to the activity layout XML file?

Edit: source : http://developer.android.com/training/basics/fragments/creating.html last parargraph says :

Note: When you add a fragment to an activity layout by defining the fragment in the layout XML file, you cannot remove the fragment at runtime. If you plan to swap your fragments in and out during user interaction, you must add the fragment to the activity when the activity first starts, as shown in the next lesson.

Thanks in advance.

Upvotes: 0

Views: 962

Answers (2)

Filipe Silva
Filipe Silva

Reputation: 220

If the fragments are defined in Xml you won't be able to change them at runtime; in that case I'd suggest using an <include layout="@layout/my_inner_layout"/> tag, that is not only better performance-wise as it is easier to use (you can access the views defined in my_inner_layout.xml using findViewById() method from the host activity).

Upvotes: 0

Heshan Sandeepa
Heshan Sandeepa

Reputation: 3688

You can use fragments in two ways ,

  1. Static Fragments

Here you can define the fragment in whatever the layout file you need. Only thing is, that defined fragment can not be change at the run time. So, re-usability will be issue here, you cant take the advantage of the re-usability of fragments in this case.

  1. Dynamic Fragments

Here you can define a place holder(frame layout etc) on your layout and you can add/replace whatever the fragment you expect at any time while your activity is running. This ensure the re-usability.

Also you can use backStack if back navigation is required.

So, it depend on your requirement.

Upvotes: 1

Related Questions