๐Ÿ”ฅTIL๐Ÿ”ฅ์ŠคํŒŒ๋ฅดํƒ€ | ViewPager2

hyihyiยท2024๋…„ 1์›” 16์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
33/70
post-thumbnail

1. Gradle์— ViewPager2 ์˜์กด์„ฑ ์ถ”๊ฐ€

implementation ("androidx.viewpager2:viewpager2:1.0.0")

2. ๋ ˆ์ด์•„์›ƒ์— ViewPager2 ์ถ”๊ฐ€

<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" />

3. ํ”„๋ž˜๊ทธ๋จผํŠธ ์ƒํƒœ ์–ด๋Œ‘ํ„ฐ์ธ ViewPagerAdapter ์ƒ์„ฑ

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)

// BottomNavigationView์™€ ViewPager2๋ฅผ ์—ฐ๊ฒฐ
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
}

// ViewPager2์˜ ํŽ˜์ด์ง€ ๋ณ€ํ™”์— ๋”ฐ๋ผ BottomNavigationView์˜ ์„ ํƒ๋œ ํƒญ์„ ์—…๋ฐ์ดํŠธ
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
    override fun onPageSelected(position: Int) {
        binding.navView.menu.getItem(position).isChecked = true
    }
})
profile
๋‚ด๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์“ฐ๋Š” ๋ธ”๋กœ๊ทธ

0๊ฐœ์˜ ๋Œ“๊ธ€