嗨,我正在看着android网站上的以下片段例子。
http://developer.android.com/guide/components/fragments.html#Example
我想知道为什么执行某些方法。
为什么例如在detailsFragment中执行以下方法:
public static DetailsFragment newInstance(int index) { DetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); return f; }您是否也不能简单地实例化DetailsFragment并使用setter方法设置index 。 绕过整个setArguments 。
首先使用setArguments的要点是什么? 你不可以只使用设定器和吸气器吗?
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 know why certain methods are performed.
Why for instance, in the detailsFragment is the following method performed:
public static DetailsFragment newInstance(int index) { DetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); return f; }Could you not also simply instantiate the DetailsFragment and use a setter method to set index instead. Bypassing the whole setArguments.
What's the point of using setArguments in the first place? Could you not just use setters and getters?
最满意答案
您可以使用getter和setter,但是通过传递一个bundle,你不需要编写该代码,因为它已经在那里了。 此外,我相信如果屏幕方向改变,这些参数会自动传递,这也使生活更轻松。
基本上,setArguments和getArguments只是Google建议您遵循的设计模式:
每个片段都必须有一个空构造函数,因此可以在还原其活动状态时将其实例化。 强烈建议子类没有其他具有参数的构造函数,因为这些构造函数在重新实例化时不会被调用; 相反,参数可以由调用者使用setArguments(Bundle)提供,稍后由片段使用getArguments()检索。 http://developer.android.com/reference/android/app/Fragment.html
我采取这一点包括您的片段操作所需的设置器。 再一次 - 没有什么可以强迫你这样做,而且你知道 - 这不是唯一可以做的事情。
You can use getters and setters, but by passing in a bundle you don't need to write that code, since it's already there. Also, I believe that these arguments are automatically passed in again if the screen orientation changes, which also makes life easier.
Essentially, setArguments and getArguments is just a design pattern that Google suggests you follow:
Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments(). http://developer.android.com/reference/android/app/Fragment.html
I take that to include setters which are needed for your Fragment to operate as well. Then again - there's nothing forcing you to do it this way, and as you know - it's not the only way things could be made to work.
更多推荐
发布评论