How to transfer some data to another Fragment?

前端 未结 10 2020
说谎
说谎 2020-11-22 11:41

How to transfer some data to another Fragment likewise it was done with extras for intents?

10条回答
  •  悲&欢浪女
    2020-11-22 12:26

    To extend the previous answer even more, like Ankit was saying, for complex objects you need to implement Serializable. For example, for the simple object:

    public class MyClass implements Serializable {
        private static final long serialVersionUID = -2163051469151804394L;
        private int id;
        private String created;
    }
    

    In you FromFragment:

    Bundle args = new Bundle();
    args.putSerializable(TAG_MY_CLASS, myClass);
    Fragment toFragment = new ToFragment();
    toFragment.setArguments(args);
    getFragmentManager()
        .beginTransaction()
        .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
        .addToBackStack(TAG_TO_FRAGMENT).commit();
    

    in your ToFragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
        Bundle args = getArguments();
        MyClass myClass = (MyClass) args
            .getSerializable(TAG_MY_CLASS);
    

提交回复
热议问题