SoFunction
Updated on 2025-04-06

Android BottomNavigationView combined with ViewPager to implement the bottom navigation bar steps

ViewPager2 Introduction

ViewPager2 is a ViewPager re-written based on RecyclerView, which has many advantages over the original ViewPager.

For basic use of ViewPager2, please refer to:/training/animation/screen-slide-2?hl=zh-cn

first step

To write a layout, please refer to other materials if you are not familiar with DataBinding.

<?xml version="1.0" encoding="utf-8"?>
<layout>
   <data>
   </data>
   < xmlns:andro
       xmlns:app="/apk/res-auto"
       xmlns:tools="/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".MainActivity">
      <androidx..ViewPager2
          android:
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="horizontal"
          app:layout_constraintTop_toTopOf="parent"
          />
      <
          android:
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          app:labelVisibilityMode="labeled"
          app:layout_constraintBottom_toBottomOf="parent"
          app:menu="@menu/bottom_view"
          />
   </>
</layout>```
# Step 2 to write Menu```kotlin
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:andro>
    <item
        android:
        android:icon="@mipmap/ic_launcher"
        android:title="A" />
    <item
        android:
        android:icon="@drawable/ic_launcher_background"
        android:title="B" />
</menu>

Step 3 Writing Fragment

The code is not displayed here. I used the template code of AS to create two Fragments: AFragment and BFragment.

Step 4: Write the Adapter for ViewPager2

ViewPager2 uses FragmentStateAdapter as its Adapter.

class ViewPagerAdapter(fragmentActivity: FragmentActivity,private  val fragments:Map<Int,Fragment>) :FragmentStateAdapter(fragmentActivity){
    override fun getItemCount(): Int {
        return 
    }
    override fun createFragment(position: Int): Fragment {
       return fragments[position]!!
    }
}

Step 5: Correlate ViewPager2 and BottomNavigationView

Activity code:

class MainActivity : AppCompatActivity() {
    var binding:ActivityMainBinding?=null
    private val fragments= mapOf&lt;Int,Fragment&gt;(
        A to ("1","2"),
        B to ("3","4")
    )
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        binding=((this))
        setContentView(binding?.root)
        binding?.apply {
            =ViewPagerAdapter(this@MainActivity,fragments)
            BnvMediator(bnv, vp2) { bnv, vp2 -&gt;
                 = true//False ViewPager2 cannot slide                =null//The icon showing the BottomNavigationView.            }.attach()
        }
    }
    companion object{
        private val A:Int=0
        private val B:Int=1
    }
}

Associated tool classes:

class BnvMediator(
    private val bnv: BottomNavigationView,
    private val vp2: ViewPager2,
    private val config: ((bnv: BottomNavigationView, vp2: ViewPager2) -&gt; Unit)? = null
) {
    //The correspondence between the menu item that stores bottomNavigationView and its own position    private val map = mutableMapOf&lt;MenuItem, Int&gt;()
    init {
        //Initialize the corresponding relationship between item and index of bnv         { index, item -&gt;
            map[item] = index
        }
    }
    /**
      * Selection relationship between BottomNavigationView and ViewPager2
      */
    fun attach() {
        config?.invoke(bnv, vp2)
        (object : () {
            override fun onPageSelected(position: Int) {
                (position)
                 = [position].itemId
            }
        })
         { item -&gt;
             = map[item] ?: error("No correspondence${}ofViewPager2of元素")
            true
        }
    }
}

This is the article about the detailed explanation of the steps to implement the bottom navigation bar in Android BottomNavigationView combined with ViewPager. For more related contents of the bottom navigation bar in Android BottomNavigationView, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!