有两个fragment分别为FragementA和FragmentB,现在要从FragementA跳转到FragmentB。同时要向FragmentB中传入数据,首先要在FragmentB中创建静态的方法,如下:
public static FragmentB getInstance(ObjectA object) { FragmentB fragment = new FragmentB(); Bundle bundle = new Bundle(); bundle.putSerializable(Constants.BundleKey.Object, result); fragment.setArguments(bundle); return fragment; }
在FragementA中跳转的时候:
FragmentB fragment = FragmentB .getInstance(result); addFragmentToStack(fragment, true, true);
protected void addFragmentToStack(final Fragment fragment, final boolean isAddToBack, boolean hasAnimation) { FragmentTransaction ft = getFragmentManager().beginTransaction(); try { if (hasAnimation) { ft.setCustomAnimations(R.anim.slide_right_in, R.anim.slide_left_out, R.anim.slide_left_in, R.anim.slide_right_out); } } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException( "动画数组下标越界"); } ft.add(R.id.fragment_container, fragment); if (isAddToBack) { ft.addToBackStack(null); } ft.commit(); }这样就实现了fragment跳转的时候传递数据,在FragmentB中要把传递的数据取出,否则传数据就没有意义了,代码:
ObjectA object = (ObjectA) getArguments().getSerializable(Constants.BundleKey.Object);其中ObjectA这个类要实现Serializable方法,否则也是不能传递的,切记切记!!