In this post i will show how to implement a Nested ViewPager as an BottomNavigationView item. I accept that this much nesting is not a good user experience but sometimes you just need to do it Below you see a screen recording of the final app. As you see in the screen recording, bottom consists of three menu items. Each menu item loads a Fragment. Notifications menu item loads a ViewPager and first page of the ViewPager is another ViewPager.
Let’s start with Main Activity,its layout and bottom navigation view menu:
There will be many Fragments in the app and they need to show themselves. The FrameLayout (fragment_container) is the place for that. Fragments will use this layout as a container.
In onCreate of the Activity, we initialize the BottomNavigationView and add the initial Fragment to the layout. Initial Fragment is the FirstFragment. On BottomNavigationItemSelectedListener, depending on the clicked menu item, we replace the Fragment showing content in fragment_container. FirstFragment and SecondFragment are just simple Fragments displaying a text. Third one is a ViewPager Fragment where its first page is a view pager,too.
Now,let’s see the ViewPagerFragment code:
Key point here is using ChildFragmentManager when creating the ViewPagerAdapter. In order to manage Fragments inside a Fragment, you need to use ChildFragmentManager. We are using a FragmentStatePagerAdapter here. There is a greate blog post here, you can learn more about the Fragment Pager Adapters. In getItem method of the adapter, we return the Fragment instance that we want to display. First fragment is again a View Pager, and second Fragment is again a simple Fragment. Source code of InnerViewPager is identical to this ViewPager code.
Hope this post helps you.
Full source code is here.