I am trying to access the parent viewpager from inside a fragment, but i have no idea how to do that. I need to switch the currentItem on the ViewPager after a onClick event inside the fragment.
Any ideas?
EDIT:
I want access to the parent view(ViewPager View) so that i can change the currentItem which is visible, from inside one of my fragments.
From fragment, call getActivity() which will gives you the activity in which the fragment is hosted. Then call findViewById(ViewPagerId) to get the ViewPager.
ViewPager - How It Works The idea is that ViewPager works with a PageAdapter to supply the Views that represent each page. The basic idea is that ViewPager keeps track of what page should be visible on the screen and then asks the PagerAdapter to get the View hierarchy that needs to be displayed.
ViewPager is a layout manager that allows the user to flip left and right through pages of data. It is mostly found in apps like Youtube, Snapchat where the user shifts right – left to switch to a screen. Instead of using activities fragments are used.
From fragment, call getActivity() which will gives you the activity in which the fragment is hosted. Then call findViewById(ViewPagerId) to get the ViewPager.
ViewPager vp=(ViewPager) getActivity().findViewById(ViewPagerId);
Edit: I must add, even though Eldhose answer's works, I would defend my approach. Because the less the fragment knows about the Activity containing it, the better. By doing this, you can get the parent view without depending on IDs, and you can still get information from it even if it isn't a ViewPager.
You can get the in the Fragment's onCreateView
method.
The container
param is the parent View, in that case, a ViewPager.
In Java:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewPager pager = (ViewPager) container; //.... Rest of your method }
Kotlin Version:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle) { val pager = container as ViewPager //.... Rest of your method }
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