4.5 Fragment Slide Shows

A common way to use a fragment is with a ViewPager, which is a container that allows swapping of fragments without changing the entire screen. We’ll be creating a simplified version of the menu view in Eatery:

1. We will first create the classes for our two fragments: LunchFragment and DinnerFragment.

LunchFragment.kt
class LunchFragment: Fragment() {
  companion object {
    fun newInstance(): LunchFragment {
      return LunchFragment()
    }
  }
  override fun onCreateView(inflater: LayoutInflater, 
                            container: ViewGroup?, 
                            savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_layout, container, false)
  }
}
DinnerFragment.kt
class DinnerFragment: Fragment() {
  companion object {
    fun newInstance(): DinnerFragment {
      return DinnerFragment()
    }
  }
  override fun onCreateView(inflater: LayoutInflater, 
                            container: ViewGroup?, 
                            savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_layout, container, false)
  }
}

Because a fragment inherits a different parent than an activity, if we want to use activity-specific methods like findViewById(), we'll need access to the root view. We can easily modify the code inside the onCreateView() method.

2. We create a view pager adapter class to manage the changing of fragments. As we can see in the code, each page in the view pager is associated with a fragment.

3. We add the view pager adapter to our activity.

The XML to our activity may look something like this, where there is a container for holding the view pager.

As you can see, setting up a view pager doesn't take too many steps and there is not too much boilerplate code. View pagers are versatile and appear in many mobile designs. We even used a view pager in Eatery! The launch screen of Eatery currently has a view pager with three pages and each of those pages is associated with a fragment.

Last updated

Was this helpful?