Fragment只有一个无参构造函数,并且要显式定义
用法
public static XxFragment newInstance(String text) {
XxFragment fragment = new XxFragment();
Bundle bundle = new Bundle();
bundle.putString(“name”, text);
//fragment保存参数,传入一个Bundle对象
fragment.setArguments(bundle);
return fragment;
}
}
setArguments方法的调用必须要在Fragment与Activity关联之前。 这句话可以这样理解,setArgument方法的使用必须要在FragmentTransaction的commit之前使用。
Activity重新创建时,会重新构建它所管理的Fragment,原先的Fragment的字段值将会全部丢失,但是通过Fragment.setArguments(Bundle bundle)方法设置的bundle会保留下来。所以尽量使用Fragment.setArguments(Bundle bundle)方式来传递参数
根据Android文档说明,当一个fragment重新创建的时候,系统会再次调用 Fragment中的默认构造函数。 注意这里:是 默认构造函数。
这句话更直白的意思就是:当你小心翼翼的创建了一个带有重要参数的Fragment的之后,一旦由于什么原因(横竖屏切换)导致你的Fragment重新创建。——-很遗憾的告诉你,你之前传递的参数都不见了,因为recreate你的Fragment的时候,调用的是默认构造函数。
对比
而使用系统推荐的 Fragment.setArguments(Bundle)来传递参数。就可以有效的避免这一个问题,当你的Fragment销毁的时候,其中的Bundle会保存下来,当要重新创建的时候会检查Bundle是否为null,如果不为null,就会使用bundle作为参数来重新创建fragment.
Activity 和 Fragment 的通信实例:
public class Del {
public static Bundle getBundle(Del.BaseDelegate delegate) {
Bundle bundle = new Bundle();
bundle.putParcelable(1, delegate);
return bundle;
}
public interface BaseDelegate extends Parcelable {
@Override
default int describeContents() {
return 0;
}
@Override
default void writeToParcel(Parcel dest, int flags) {}
}
public interface XXDelegate extends BaseDelegate {
void onSuccess();
}
Activity:
public class Activity{
private MainFragment mMainFragment;
…
mMainFragment = MainFragment.newInstance(Del.getBundle(mMainDelegate));
private Del.XXDelegate mDelegate = new Del.LoginDelegate() {
@Override
public void onSuccess() {
.....
}
};
}
Fragment:
private Del.MainDelegate mDelegate;
public static aFragment newInstance(Bundle args) {
aFragment fragment = new aFragment();
fragment.setArguments(args);
return fragment;
}
mDelegate = getArguments().getParcelable(1);