Setup
- Set RecyclerView to horizontal scrolling
- Use
PagerSnapHelper
to make sure each page/fragment is shown fully (no partial scroll) - Use CirclePagerIndicatorDecoration to display current page indicator
- Use LayoutContainer to enable Kotlin Android Extensions ViewBinding for ViewHolder in RecyclerView
class TestPagerActivity : AppCompatActivity() { private lateinit var adapter: LocalAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // optional: hide title/actionbar supportActionBar?.hide() setContentView(R.layout.testpager) initUi() } private fun initUi() { adapter = LocalAdapter() list.adapter = adapter val snapHelper = PagerSnapHelper() snapHelper.attachToRecyclerView(list) list.addItemDecoration(CirclePagerIndicatorDecoration()) } class LocalAdapter: RecyclerView.Adapter<LocalAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalAdapter.ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.testpager_page, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: LocalAdapter.ViewHolder, position: Int) { when(position) { 0 -> { holder.textView.text = "Page #1" } 1 -> { holder.textView.text = "Page #2" } 2 -> { holder.textView.text = "Page #3" } } } override fun getItemCount(): Int = 3 inner class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer }}
Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
/>
</RelativeLayout>
Modify adapter to support multiple layout.
class LocalAdapter(val viewModel: QuoteSetupViewModel, val fragmentManager: FragmentManager): RecyclerView.Adapter<LocalAdapter.ViewHolder>() { override fun getItemViewType(position: Int): Int { return when(position) { 0 -> { R.layout.quotesetup_language } 1 -> { R.layout.quotesetup_time } else -> { R.layout.testpager_page } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalAdapter.ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(viewType, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: LocalAdapter.ViewHolder, position: Int) { when(position) { 0 -> { // update holder view } 1 -> { // update holder view } 3 -> { // update holder view } } } override fun getItemCount(): Int = 3 inner class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer}