blog-post-1

Create ViewPager using RecyclerView — Android

Usually, we use ViewPager for collection sliding views like fragments, images, or any view sections. But today I will describe how we can create it using RecyclerView.

RecyclerView usually used to show the list or any collections. Recycler View has an own scroll behaviour vertically or horizontally. For this, we have to define LayoutManager for layout behaviour. Here I am giving an example how RecyclerView declares and add layout manager:

RecyclerView rvBotCollection;
            rvBotCollection =(RecyclerView)itemView.findViewById(R.id.rvCollectionList);
            

Then an adapter will add to show the whole list with item view. Now we can make it horizontally scroll-able like this:

rvBotCollection.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
            

Now RecyclerView will scroll in a horizontal way. But the main problem is view will scroll at a time multiple items. Using SnapHelper we can make single item scroll at a time like this way:

SnapHelper snapHelper = new PagerSnapHelper();
            snapHelper.attachToRecyclerView(rvBotCollection);
            

Then you will see the magic RecyclerView will behave like a ViewPager.

Uses area: Image Slider, Product Slider, View Slider etc.

Thank you and Happy Coding :)