Android: How to send data from parent fragment to child fragment

If you have some parameters to pass to fragment which is defined through XML, I think better and simple option is to add it dynamically. In that case you can pass two params, param1 and param2 to the child fragment like this:

public static YourFragment newInstance(String param1, String param2) {
        YourFragment fragment = new YourFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public YourFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

The newInstance() method stores the parameters in the arguments bundle of the bundle. It will be useful when Android recreates the fragment. In that case, the parameters are retrieved in the onCreate() method.


You can use interface for this. Create interface in your parent fragment and create it's object and getter-setter method.

interface YourListner{
    void methodToPassData(Object data);
}

static YourListner listnerObj;

public void setListnerObj(YourListner listnerObj) {
    this.listnerObj = listnerObj;
}

Implement it in your child fragment.

Then, add following code in parent fragment.

ChilefragmentName yourfrag=((ChilefragmentName) getSupportFragmentManager().findFragmentById(R.id.fragmentId))
if(yourfrag !=null)
    {
        //Set listner
      yourfrag.setListnerObj((ChilefragmentName)yourfrag);

    }
if(listnerObj!=null)
    {
        //Pass your data
        listnerObj.methodToPassData(data);

    }

You can handle that data in implemented method in your child fragmen.


Simple solution is to get reference on your child fragment in your parent fragment onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    View view = inflater.inflate(R.layout.parent_fragment, container, false);
    YourChildFragment fragment = (YourChildFragment) getChildFragmentManager().findFragmentById(R.id.child_fragment_id);

    // pass your data
    fragment.setMyInt(42);

    return view;
}