最近有一个需求,需要在打开一个fragment的时候通过构造方法传参的方式传入数据。但是当我在fragment里面进行有参构造方法的时候。报以下的错:
报错:Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead less… (Ctrl+F1)
From the Fragment documentation: 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().
如上图所示,但是通过报错的信息中可以看到,官方是让我们以Bundle的方式传递数据。最后通过查资料,通过以下方式得以解决:
通过静态方法去得到fragment的对象:
public static TestFragment newInstance(List<Card> List) {
TestFragment newInstance = new TestFragment();
Bundle bundle = new Bundle();
bundle.putParcelableList("param", List);
newInstance.setArguments(bundle);
return newInstance;
}
然后在fragment的onCreate()方法里面去得到数据。然后再去做相应的操作
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args=getArguments();
if(args!=null){
、List = args.getParcelableArrayList("param");
}
}