最近在做项目的途中遇到了问题,本来想着在fragment中创建一个构造参数来传递数据,获取Activity中的数据,如下:
public class FaultVideoFragment extends android.app.Fragment {
private FaultEnclosureModel model2;
private FaultDetailsActivity faultDetailsActivity;
private FaultEnclosureBean faultEnclosureBean;
private RepairDetailActivity repairDetailActivity;
// public static String bizId;
@BindView(R.id.gridView)
GridView gridView;
@BindView(R.id.rl_isShow)
RelativeLayout rlIsShow;
private View view;
private int tag = 0;
public FaultVideoFragment(int tag){
this.tag = tag;
}
这种写法debug测试的时候没有问题的,但是在打包release版本时出现如下错误
D:\HZZX\sw023_meis\code\android\Meiz\app\src\main\java\com\hzzx\meiz\fragment\fault\FaultPhotoFragment.java
Error:Error: This fragment should provide a default constructor (a public constructor with no arguments) (com.hzzx.meiz.fragment.fault.FaultPhotoFragment) [ValidFragment]
错误说要使用默认构造函数外加setArguments(Bundle)来代替,去 Android 的官网上查看Fragment的例子都是下面这个样子的:
CharSequence mLabel;
/**
* Create a new instance of MyFragment that will be initialized
* with the given arguments.
*/
static MyFragment newInstance(CharSequence label) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putCharSequence("label", label);
f.setArguments(b);
return f;
}
去掉带参的构造方法,写一个newInstance静态方法,参数为我们需要传递的数据:
public class FaultVideoFragment extends android.app.Fragment {
private FaultEnclosureModel model2;
private FaultDetailsActivity faultDetailsActivity;
private FaultEnclosureBean faultEnclosureBean;
private RepairDetailActivity repairDetailActivity;
// public static String bizId;
@BindView(R.id.gridView)
GridView gridView;
@BindView(R.id.rl_isShow)
RelativeLayout rlIsShow;
private View view;
private int tag = 0;
public static FaultVideoFragment newInstance(int tag) {
FaultVideoFragment newFragment = new FaultVideoFragment();
Bundle bundle = new Bundle();
bundle.putInt("tag", tag);
newFragment.setArguments(bundle);
return newFragment;
}
然后再fragment的OnCreate方法中这样获取:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
if (args != null) {
tag = args.getInt("tag");
}
super.onCreate(savedInstanceState);
}
在Activity中我们这样发送数据:
FaultVideoFragment faultVideoFragment = FaultVideoFragment.newInstance(2);