I have a ViewPager using a TabLayout with several fragments. I would like to click a button from one of the ViewPager fragments and direct the user to another tab/fragment using the tab name.
When the button is clicked, I would like the TabLayout to change as well as show the fragment associated to that tab. I would also need to send additional data with the request to show on the new fragment.
I don't have access to the ViewPager setCurrentItem(int index). Ideally I would like to communicate with the parent to complete the request.
What you need to do is to create a callback from the Child Fragment to the Parent Fragment. In the Onclick in your Child Fragment, call the callback to the Parent Fragment and then in the Parent Fragment, replace the Child Fragment with the desired Fragment.
Architectural structure of an Android single-activity screen This means that a single activity as a parent can have one or more fragments as children. Only the fragments are replaced within an event or navigation, so that the original parent activity continues to function as a container.
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
You should write a method in the parent (containing the ViewPager and the sub-fragments) like so:
public void setPagerFragment(int a)
{
pager.setCurrentItem(a);
}
This will set the current Fragment in the ViewPager to be the one specified. You can then call this method from the child Fragment with:
int newFrag = 0; //the number of the new Fragment to show
ParentActivity parent = (ParentActivity) getActivity();
parent.setPagerFragment(newFrag);
Regarding sending additional data with the request to show on the new fragment, you can make another method in the parent, to be called in the child, which will set some data in the parent, which the parent can then use when setting the new fragment.
For example in the parent:
public void setExtraData(Object data)
{
dataFromChildFrag = data;
}
And use this in the child like so:
String data = "My extra data"; //the number of the new Fragment to show
ParentActivity parent = (ParentActivity) getActivity();
parent.setExtraData(data);
Finally, if the parent is in fact a Fragment itself rather than an Activity, simply replace all references of:
ParentActivity parent = (ParentActivity) getActivity();
to:
ParentFragment parent = (ParentFragment) getParentFragment();
I hope this helps!
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