<com.google.android.material.tabs.TabLayout
android:id=“@+id/tabLayout”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”/>
<androidx.viewpager2.widget.ViewPager2
android:id=“@+id/viewpager”
android:layout_width=“match_parent”
android:layout_height=“240dp”/>
定义RecyclerView Adapter和单元布局
class DemoViewPagerAdapter : RecyclerView.Adapter<DemoViewPagerAdapter.EventViewHolder>() {
val eventList = listOf(“0”, “1”, “2”)
// Layout “layout_demo_viewpager2_cell.xml” will be defined later
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
EventViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.layout_demo_viewpager2_cell, parent, false))
override fun getItemCount() = eventList.count()
override fun onBindViewHolder(holder: EventViewHolder, position: Int) {
(holder.view as? TextView)?.also{
it.text = "Page " + eventList.get(position)
val backgroundColorResId = if (position % 2 == 0) R.color.blue else R.color.orange)
it.setBackgroundColor(ContextCompat.getColor(it.context, backgroundColorResId))
}
}
class EventViewHolder(val view: View) : RecyclerView.ViewHolder(v