ViewPager2の導入
自分がViewPager2の導入につまづいたことがあるため、ハマりどころなどを挙げながら導入するまでをひと通りやってみます。
ViewPager2とViewPagerが存在する
そもそもハマってしまった問題として、「ViewPager」と「ViewPager2」が存在します。紛らわしいので注意してください。
ライブラリの追加
以下のライブラリを追加します。
// ViewPager2
implementation "androidx.viewpager2:viewpager2:1.0.0"、
implementation "com.google.android.material:material:1.2.0-alpha05"
レイアウトファイルの変更
ここでも注意なのがパレットに用意されているViewPagerはViewPager2とは異なる物なので、XMLファイルをテキストで編集して仮に、
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PagerFragment">
<androidx.viewpager2.widget.ViewPager2
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
とします。
レイアウトファイルは準備完了です。
ViewPager2のアダプター作成
続いて、ViewPager2のためのアダプターを作成します。
class PageAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
companion object {
const val NUM_PAGES = 3
}
override fun getItemCount(): Int = NUM_PAGES // Pagerの画面数
// ページを切り替えた時、表示するページの設定
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> Page1Fragment()
1 -> Page2Fragment()
2 -> Page3Fragment()
else -> SliderPage1Fragment()
}
}
}
あとはフラグメントに、作成したアダプターをセットします。
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity?.let { fa ->
pager.adapter = PagerAdapter(fa)
}
}
以上で完了です。左右スワイプでページの切り替えが出来ます。
まとめ
とにかくViewPager2とViewPagerが紛らわしく、パレットにもViewPager2が無いことがややこしくなる原因だと思います。