Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So I have viewed other questions, and I have not been able to come up with a solution. So basically, I have a parent fragment and a child fragment and I need to pass an integer to the child fragment. The child fragment is defined in the XML, so I am not able to attach a bundle as far as I know. It seems like it should be simple but I have not been able to figure it out.

Any help on how to do this would be great. Thanks!

like image 472
kvel Avatar asked Aug 05 '15 04:08

kvel


2 Answers

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;
}
like image 189
Stas Parshin Avatar answered Sep 19 '22 15:09

Stas Parshin


You can use arguments to pass extra data to fragments. This method works in general, not only with XML params.

...

ChildFragment cf = new ChildFragment();

Bundle b = new Bundle();
b.putInt("myInt", 0);

MyData data = new MyData();
b.putSerializable("myObject", data); // Pass entire objects

cf.setArguments(b);

...

transaction.commit();

You can than obtain the data with the getArguments interface

...
MyData data = (MyData) getArguments.getSerializable('myObject');
...
like image 38
Joris Lamers Avatar answered Sep 20 '22 15:09

Joris Lamers