Search code examples
androidkotlinandroid-viewpager2

ViewPager2 without Fragments


I have an application and I need to realize a behavior where I have an XML layout that I need to apply for every ViewPager2 page NOT USING FRAGMENTS. Is there an opportunity?

I have an ArrayList and regarding his size I need to create the same amount of pages in ViewPager2 and fill every page with an info in my array. There can be plenty of pages, that's why I don't want to create a fragment for every page.


Solution

  • ViewPager2 is essentially a RecyclerView wrapper that adds layout and touch handling to account for items that have size of a page (fill entire widgets size).

    setAdapter(RecyclerView.Adapter adapter) lets you use any recycler view adapter. There was never a requirement to use a FragmentStateAdapter.

    So just implement a normal recycler view adapter and your pages will be displayed using view holders (that are created using your XML layout).