For the More Curious: Why Use Fragment Arguments?

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
54.152.43.79