Reputation:
I need to show a fixed-length list of items like below:
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!
Upvotes: 3
Views: 4429
Reputation:
Both pskink and Anthony Cannon answers are great. We can implement recycling mechanism PagerAdapter like this: https://stackoverflow.com/a/19020687/5154523
Upvotes: 0
Reputation: 1273
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.
Upvotes: 3