Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Parent ViewPager View from inside Fragment

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.

like image 985
Manak Kapoor Avatar asked Aug 28 '12 05:08

Manak Kapoor


People also ask

How to access ViewPager from fragment?

From fragment, call getActivity() which will gives you the activity in which the fragment is hosted. Then call findViewById(ViewPagerId) to get the ViewPager.

How ViewPager works?

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.

What is ViewPager for?

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.


2 Answers

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); 
like image 198
Eldhose M Babu Avatar answered Oct 13 '22 00:10

Eldhose M Babu


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     } 
like image 22
Vitor Hugo Schwaab Avatar answered Oct 13 '22 00:10

Vitor Hugo Schwaab