Fragment强烈要求构造方法为空

在使用Fragment的时候,常常需要传递参数,一般想法是直接在构造方法中传递参数,但是查阅官方文档发现:


Fragment ()
Default constructor. 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().


这段话的意思是Fragment的构造方法不能带参数,如果要传递参数,可以用setArguments(Bundle)传递Bundle对象,然后在Fragment用getArguments(Bundle)获取Bundle对象,从而获取参数。


比如:
在我们的Fragment中添加如下方法:


public static MyFragment newInstance(String param1, String param2) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putString("Param1", param1);
args.putString("Param1", param2);
fragment.setArguments(args);
return fragment;


需要传递参数创建MyFragment的时候就使用这种方法,然后在MyFragment中使用 getArguments().getString(”Param1”) 获取参数。
关于为什么不能使用有参数的构造方法,可以看一下这一篇:

浅析Fragment为什么需要空的构造方法

猜你喜欢

转载自blog.csdn.net/snailpeople/article/details/77726452