A ViewPager
is a ViewGroup
that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter
to generate the pages that the view shows.
Create a custom Pager Adapter
// override 4 methods as shown below
class MyPagerAdapter: PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val inflater = LayoutInflater.from(container.context)
val view = when {
position == 0 -> inflater.inflate(R.layout.layout1, container, false)
position == 1 -> inflater.inflate(R.layout.layout2, container, false)
position == 2 -> inflater.inflate(R.layout.layout3, container, false)
else -> {
inflater.inflate(R.layout.layout1, container, false)
}
}
// add the view to the container
container.addView(view, 0)
return view
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
override fun getCount(): Int {
return 3
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
}
Inside the Activity's onCreate
add the adapter to the ViewPager
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager.adapter = MyPagerAdapter()
}
}