What are the advantages of adding a fragment via XML vs programmatically?

Viewed 217

From the Android documentation it's not very clear to me which are the advantages and practical use cases of adding fragments via XML compared to adding them programmatically.

Do both methods allow sending data from the activity to the fragment and back using Bundle?
Can both methods behave similarly in the activity lifecycle?

Some short examples or references will surely help.

3 Answers

Both the methods have only slight difference. If you add fragment in XML, then you are first loading or creating it then you will get its instance and vice-versa for the other approach.

Also, programmatically adding fragment gives you advantage of changing its attributes dynamically whereas you have fixed values if you add it from XML.

Not that much major difference it has.

With FragmentContainerView and using the android:name or android:class, you can avoid the boiler plate code of instantiating the fragment only when savedInstanceState is null or when it is not already added.

If you do that programmatically, you need to make sure that you only add the fragment if it is not already added to the activity by checking:

if (getSupportFragmentManager().findFragmentByTag(CUSTOM_TAG) != null)
{
     // You can also easily add animations or pass custom data.
     getSupportFragmentManager().beginTransaction().add(R.id.container_view, YourFragment.newInstance(data), CUSTOM_TAG).commit();
}

Programmatically doing it gives you advantages of passing custom data, adding it when you actually need it. In case of layout method, it will be instantiated when the activity's layout gets inflated. But many times, we don't need to add a fragment immediately, adding it programmatically would be a better option in that case.

No difference at all. Android has a system for instantiating objects from XML, but it's always interchangeable with actually executing constructors and the methods to add children. The difference is convenience: The XML system allows you to easily link other resources and it has features to help with passing the right parameters.

Related