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.
You should write a method in the parent (containing the ViewPager and the sub-fragments) like so:
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:
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:
And use this in the child like so:
Finally, if the parent is in fact a Fragment itself rather than an Activity, simply replace all references of:
to:
I hope this helps!
the easiest way to achieve this, using an EventBus framework!
I prefer(ed) using EventBus by greenRobot
How to implement:
1) Create an event class which fulfills your needs
2) prepare your subscribers! In your case this would be the Activity which holds the reference to the tab layout:
3) and finally: post the event from your OnClickListener insider your fragment: