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!
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;
}
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');
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With