Search code examples
androidandroid-fragmentsbundlefragment-lifecycle

What is the purpose of a Fragment bundle if the parent Activity bundle always has the objects that are passed to the Fragment?


I have a model inside an Activity, and a Fragment within this Activity needs access to it. I am currently passing it through the Fragment bundle, but why can't I just access it from the Activity within the fragment?

For example, I would use this code inside the fragment onCreate():

Model model = ((ActivityWithModel) getActivity).getModel();

In general, why cant this always be the method in which the Activity and Fragment share objects, or in which the Activity passes the parameters to the Fragment? Why is the Fragment bundle needed?


Solution

  • Using getActivity() makes your Fragment dependent on that particular Activity class. If you would want to reuse the same Fragment in several unrelated activities you may want to avoid that. Also you can test your Fragment easier

    Then getActivity() is not always available, it only available starting from Fragment's onActivityCreated(). Sometimes you want to pass the parameters earlier such as to Fragment's onCreate() so you have to use Bundle for that