1. Fragment 使用时要有一个无参构造函数
/** * Create a new instance of a Fragment with the given class name. This is * the same as calling its empty constructor. * * @param context The calling context being used to instantiate the fragment. * This is currently just used to get its ClassLoader. * @param fname The class name of the fragment to instantiate. * @param args Bundle of arguments to supply to the fragment, which it * can retrieve with {@link #getArguments()}. May be null. * @return Returns a new fragment instance. * @throws InstantiationException If there is a failure in instantiating * the given fragment class. This is a runtime exception; it is not * normally expected to happen. */ public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) { try { Class clazz = sClassMap.get(fname); if (clazz == null) { // Class not found in the cache, see if it's real, and try to add it clazz = context.getClassLoader().loadClass(fname); sClassMap.put(fname, clazz); } Fragment f = (Fragment)clazz.newInstance(); if (args != null) { args.setClassLoader(f.getClass().getClassLoader()); f.mArguments = args; } return f; } catch (ClassNotFoundException e) { throw new InstantiationException("Unable to instantiate fragment " + fname + ": make sure class name exists, is public, and has an" + " empty constructor that is public", e); } catch (java.lang.InstantiationException e) { throw new InstantiationException("Unable to instantiate fragment " + fname + ": make sure class name exists, is public, and has an" + " empty constructor that is public", e); } catch (IllegalAccessException e) { throw new InstantiationException("Unable to instantiate fragment " + fname + ": make sure class name exists, is public, and has an" + " empty constructor that is public", e); } }
2. 给 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 通信
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 } } }
:http://www.linuxidc.com/Linux/2017-05/144200.htm