3

I need to show a fixed-length list of items like below: enter image description here

Which approach should I use? ViewPager or Horizontal RecyclerView. And what is the advantages (performance, ...) of ViewPager/Horizontal RecyclerView over the other in this case? Thanks in advance!

  • 2
    Possible duplicate of [RecyclerView vs ViewPager](https://stackoverflow.com/questions/38167839/recyclerview-vs-viewpager) – denvercoder9 May 31 '18 at 10:41
  • Hi, I see some projects using ViewPager to do this task. I want to know what is the best approach? And why? Thanks! –  May 31 '18 at 10:44
  • Update you question and tags with what languages you are using please? Java, Kotlin, xml? – Anthony Cannon May 31 '18 at 10:46

2 Answers2

3

Performance

So in terms of performance, I would most likely always go with RecyclerView as it recycles items when they are off screen, were as the ViewPager doesn't.

How to

So todo this, you need to set the orientation of your RecyclerView to horizontal.

xml:

android:orientation="horizontal"

or Java (runtime):

LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
myRecyclerView.setLayoutManager(layoutManager);

Then to get the RecyclerView to act like a ViewPager and snap to items, you can use a LinearSnapHelper.

Everything you are looking for is actually explained in a nice tutorial here. Or if you want to dive in and just look and learn for yourself, here is the GitHub link of the tutorials sample project.

Anthony Cannon
  • 1,245
  • 9
  • 20
  • 2
    PagerAdapter docs say: *"PagerAdapter is more general than the adapters used for AdapterViews. Instead of providing a View recycling mechanism directly ViewPager uses callbacks to indicate the steps taken during an update. A PagerAdapter may implement a form of View recycling if desired or use a more sophisticated method of managing page Views such as Fragment transactions where each page is represented by its own Fragment."* - so its up to you how you do that – pskink May 31 '18 at 11:15
  • ViewPager does recycle items when they are off screen. you can control this behavior using `viewPager.setOffscreenPageLimit` – M.kazem Akhgary Nov 23 '18 at 18:00
0

Both pskink and Anthony Cannon answers are great. We can implement recycling mechanism PagerAdapter like this: https://stackoverflow.com/a/19020687/5154523