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为什么需要空的构造方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值