我们知道,Activity 在一些特殊状况下会发生 destroy 并重新 create 的情形,比如屏幕旋转、内存吃紧时;对应的,依附于 Activity 存在的 Fragment 也会发生类似的状况。而一旦重新 create 时,Fragment 便会调用默认的无参构造函数,导致无法执行有参构造函数进行初始化工作。
好在 Fragment 提供了相应的 API 帮助我们解决这个问题。利用 bundle 传递数据,参考代码如下:
public static OneFragment newInstance(int args){
OneFragment oneFragment = new OneFragment();
Bundle bundle = new Bundle();
bundle.putInt("someArgs", args);
oneFragment.setArguments(bundle);
return oneFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
int args = bundle.getInt("someArgs");
}
为什么要在这里利用bundle传递数据呢?为什么不能构造方法Constructor传递数据呢?
因为 而一旦重新 create 时,Fragment 便会调用默认的无参构造函数,导致无法执行有参构造函数进行初始化工作。