What's the point of setArguments?

前端 未结 4 1646
忘了有多久
忘了有多久 2020-12-13 03:55

Hi I was looking at the following Fragments example on the android site.

http://developer.android.com/guide/components/fragments.html#Example

I would like to

4条回答
  •  天命终不由人
    2020-12-13 04:34

    Just to add to Matthew's answer: he quoted correctly that Fragments need to have an empty constructor, so that the framework can re-instantiate them when needed.

    It is fine to use getters and setters, but as the framework may destroy and re-create your Fragment, you must ensure to not lose those parameters.

    This must be done via Fragment.onSaveInstanceState(). The saved stated will be passed back to you as the parameter savedInstanceState in Fragment.onCreate(), Fragment.onCreateView() and several other methods.

    Using Fragment.setArguments() is (in most cases, I assume) easier, at the framework will automatically preserve the arguments and thus will do most of the work for you.

    Setters may be the way to go for parameters you supply to the Fragment initially and which the fragment may adjust itself over time. Dealing with the savedInstanceState alone may be easier in this case than dealing with savedInstanceState and arguments - where you have to make a decision which is the valid parameter.

提交回复
热议问题