implementation ("androidx.viewpager2:viewpager2:1.0.0")
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toTopOf="@+id/nav_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
class ViewPagerAdapter(activity: AppCompatActivity) : FragmentStateAdapter(activity) {
private val TAB_COUNT = 3
override fun getItemCount(): Int {
return TAB_COUNT
}
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> FirstFragment()
1 -> SecondFragment()
2 -> ThirdFragment()
else -> throw IllegalStateException("Unexpected position $position")
}
}
}
4. MainActivity์์ ViewPager2์ ์ด๋ํฐ ์ฐ๊ฒฐ
val viewPager: ViewPager2 = binding.viewPager
viewPager.adapter = ViewPagerAdapter(this)
binding.navView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_contact -> viewPager.currentItem = 0
R.id.navigation_bookmark -> viewPager.currentItem = 1
R.id.navigation_myPage -> viewPager.currentItem = 2
}
true
}
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
binding.navView.menu.getItem(position).isChecked = true
}
})