使用fragment注意事项:
1.fragment一定要有一个无参构造函数
2.如果要给fragment传参,一定要使用Bundle方式传参,而不重载构造函数传参,因为在fragment重新生成的使用不会执行这个带参构造函数,而是执行无参构造函数
比如:
public static VechileFrag newInstance(Vehicle vehicle, String userId, boolean isAdd) {
VechileFrag mf = new VechileFrag();
Bundle args = new Bundle();
args.putString("userId", userId);
args.putBoolean("isAdd", isAdd);
args.putParcelable("vehicle", vehicle);
mf.setArguments(args);
return mf;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
userId = args.getString("userId");
isAdd = args.getBoolean("isAdd");
vehicle = args.getParcelable("vehicle");
if (vehicle == null) {
vehicle = new Vehicle();
}
}
}
3.fragment与activity通信,回调fragment方法。
比如fragment中定义一个接口和要回调的方法
public IVechile mIVechile;
public interface IVechile {
public void submitCarSuccess(String carId, String plateNo);
}
@Override
public void onAttach(Activity activity) {
fueltypes = FuelType.getList(activity);
try {
mIVechile = (IVechile) activity;
}
catch (Exception e) {
// TODO: handle exception
}
}
activity实现fragment的接口
1.fragment一定要有一个无参构造函数
2.如果要给fragment传参,一定要使用Bundle方式传参,而不重载构造函数传参,因为在fragment重新生成的使用不会执行这个带参构造函数,而是执行无参构造函数
比如:
public static VechileFrag newInstance(Vehicle vehicle, String userId, boolean isAdd) {
VechileFrag mf = new VechileFrag();
Bundle args = new Bundle();
args.putString("userId", userId);
args.putBoolean("isAdd", isAdd);
args.putParcelable("vehicle", vehicle);
mf.setArguments(args);
return mf;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
userId = args.getString("userId");
isAdd = args.getBoolean("isAdd");
vehicle = args.getParcelable("vehicle");
if (vehicle == null) {
vehicle = new Vehicle();
}
}
}
3.fragment与activity通信,回调fragment方法。
比如fragment中定义一个接口和要回调的方法
public IVechile mIVechile;
public interface IVechile {
public void submitCarSuccess(String carId, String plateNo);
}
@Override
public void onAttach(Activity activity) {
fueltypes = FuelType.getList(activity);
try {
mIVechile = (IVechile) activity;
}
catch (Exception e) {
// TODO: handle exception
}
}
activity实现fragment的接口