Skip to main content

How to swipe between fragments using ViewPager2 in Kotlin Android

How to swipe between fragments using ViewPager2 in Kotlin Android.

Here is a step-by-step tutorial on how to swipe between fragments using ViewPager2 in Kotlin Android:

Step 1: Create a new Android project in Android Studio and add the necessary dependencies to your app-level build.gradle file:

implementation 'androidx.viewpager2:viewpager2:1.0.0'
implementation 'androidx.fragment:fragment-ktx:1.3.0'

Step 2: Create the layout file for your activity_main.xml. Add a ViewPager2 widget to your layout:

<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Step 3: Create the layout file for your fragment_example.xml. This will be the layout for each fragment that will be displayed in the ViewPager2:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example Fragment"
android:textSize="24sp"
android:layout_gravity="center" />

</LinearLayout>

Step 4: Create a new Kotlin class for your fragment, for example, ExampleFragment.kt. In this class, override the onCreateView() method to inflate the fragment_example.xml layout:

class ExampleFragment : Fragment() {

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_example, container, false)
}
}

Step 5: In your MainActivity.kt, create a list of fragments that will be displayed in the ViewPager2:

class MainActivity : AppCompatActivity() {

private val fragments = listOf(
ExampleFragment(),
ExampleFragment(),
ExampleFragment()
)

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val viewPager: ViewPager2 = findViewById(R.id.viewPager)
val adapter = ViewPagerAdapter(fragments, this)
viewPager.adapter = adapter
}
}

Step 6: Create a new Kotlin class for your ViewPagerAdapter, for example, ViewPagerAdapter.kt. Extend the RecyclerView.Adapter class and override the necessary methods:

class ViewPagerAdapter(private val fragments: List<Fragment>, fragmentActivity: FragmentActivity) :
FragmentStateAdapter(fragmentActivity) {

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

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

Step 7: Run your app and you should be able to swipe between the fragments using the ViewPager2.

That's it! You have successfully implemented swiping between fragments using ViewPager2 in Kotlin Android.