Home » Android » android – Getting Parent ViewPager View from inside Fragment

android – Getting Parent ViewPager View from inside Fragment

Posted by: admin April 23, 2020 Leave a comment


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?


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.

How to&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);


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:

    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


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


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