Manak Kapoor
Manak Kapoor

Reputation: 982

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.

Upvotes: 35

Views: 20950

Answers (4)

Vitor Hugo Schwaab
Vitor Hugo Schwaab

Reputation: 1575

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
    }

Upvotes: 35

Muahmmad Tayyib
Muahmmad Tayyib

Reputation: 729

Another way that helped me :

                List<Fragment> fragment = getActivity().getSupportFragmentManager().getFragments();
                for (Fragment f:fragment) {
                    if (f instanceof CreatCheckInFragment){
                        ((ParentFragment) f).viewPager.arrowScroll(View.FOCUS_LEFT);
                    }
                }

Upvotes: 1

Pnemonic
Pnemonic

Reputation: 1825

The methods onCreateView and onViewCreated and onAttach are called too early.

The view is definitely attached to its parent view in the fragment's onResume method. This is a good place to then use getView().getParent()

Upvotes: 2

Eldhose M Babu
Eldhose M Babu

Reputation: 14520

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);

Upvotes: 102

Related Questions