For the More Curious: Why Use Fragment Arguments?

In this chapter you added a newInstance(…) function to your fragment to pass along arguments when creating a new instance of fragment. While this pattern is helpful from a code organization standpoint, it is also necessary in the case of fragment arguments. You cannot use a constructor to pass arguments to a fragment instance.

For instance, you might consider adding a one-argument constructor to CrimeFragment that expects a UUID crime ID as input, rather than adding a newInstance(UUID) function. However, this approach is flawed. When a configuration change occurs, the current activity’s fragment manager automatically re-creates the fragment that was hosted before the configuration change occurred. The fragment manager then adds that new fragment instance to the new activity.

When the fragment manager re-creates the fragment after a configuration change, it calls the fragment’s default, parameterless constructor. This means that after rotation, the new fragment instance would not receive the crime ID data.

So how are fragment arguments any different? Fragment arguments are stored across fragment death. The fragment manager reattaches the arguments to the new fragment it re-creates after rotation. That new fragment can then use the arguments bundle to re-create its state.

This all seems so complicated. Why not just set an instance variable on the CrimeFragment when it is created?

Because it would not always work. When the OS re-creates your fragment – either across a configuration change or when the user has switched out of your app and the OS reclaims memory – all of your instance variables will be lost. Also, remember that there is no way to cheat low-memory death, no matter how hard you try.

If you want something that works in all cases, you have to persist your arguments.

One option is to use the saved instance state mechanism. You can store the crime ID as a normal instance variable, save the crime ID in onSaveInstanceState(Bundle), and snag it from the Bundle in onCreate(Bundle?). This will work in all situations.

However, that solution is hard to maintain. If you revisit this fragment in a few years and add another argument, you may not remember to save the argument in onSaveInstanceState(Bundle). Going this route is less explicit.

Android developers prefer the fragment arguments solution because it is very explicit and clear in its intentions. In a few years, you will come back and know that the crime ID is an argument and is safely shuttled along to new instances of this fragment. If you add another argument, you will know to stash it in the arguments bundle.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.235.186.149