나만의 AI/안드로이드 도와줘

Android Kotlin [ViewPager2 알려줘]

정혜현 2024. 8. 6. 21:13

Q. 어떻게 사용해?

A. 

 

 

presentation-main-viewpager2

class MainViewPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
//    private lateinit var mainViewPagerAdapter: MainViewPagerAdapter
    private val fragments = listOf(HomeFragment(), MyFragment())

    override fun getItemCount(): Int {
        return fragments.size
    }

    override fun createFragment(position: Int): Fragment {
        return fragments[position]
    }
}

 

presentation-main

//import
import com.google.android.material.tabs.TabLayoutMediator

//onCreate
 initLayout()
 
 //뷰페이저초기화
  private fun initLayout() {
        val viewPager = binding.mainViewPager
        val mainViewPagerAdapter = MainViewPagerAdapter(this)
        viewPager.adapter = mainViewPagerAdapter

//탭레이아웃 연결
        TabLayoutMediator(binding.mainTab, binding.mainViewPager) { tab, position ->
            when (position) {
                0 -> tab.text = "검색"
                1 -> {
                    tab.text = "보관함"
                }
            }
        }.attach()
    }