Nested ViewPager in BottomNavigationView

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.

admin Hakkında

Murat Aydin works as a senior software engineer at Arcelik and develops Android apps. He has several Android applications in Google Play. He is a Sun Certified Java Developer and has eight years of experience in developing web based applications using Java technologies, and desktop and engineering applications using .Net technologies. Murat Aydin earned his BSc degree in Computer Engineering from METU (Middle East Technical University) and his MSc degree in Software Engineering from METU. He is a member of GDG Ankara (Google Developer Group Ankara, www.gdgankara.org), who organize several Android events in GDG Ankara, such as Android Developer Days. (www.androiddeveloperdays.com). twitter: @maydintr gmail: maydin