2

In my project I have an Activity that loads a list of news. When the list is loaded, this Activity is populated with the information of the first item on the list:

enter image description here

But since this loads all the news from the server, I want the user to be able to swap the news with his finger. For example: we start with news[0] and user swipe left, the content change to news[1]. The user swipe left again and the content changes to news[2] and so on... if the user swipes right, then it return to the previous news (news[1]). The header should not have a swipe movement, only the main frame (image and body should change):

enter image description here

What would be the best aproach for this behavior? I was thinking about using a TabLayout with ViewPager but I'm not sure if this is the correct way to do this. If I have something like 100 news this could be a overkill to load 100 fragments in the ViewPager right?

Does android have a better way to do this? How should I do this?

Ravers
  • 988
  • 2
  • 14
  • 45
  • 3
    No, 100 fragments is totally fine. `ViewPager` will always keep at least 3 loaded pages at time, you can configure it for more too. Also you can implement pagination to load specific number of news, like 20, then another 20, etc. – Nikola Despotoski Oct 10 '17 at 14:07
  • Another option could be a RecyclerView with a HorizontalLayoutManager such as in this answer : https://stackoverflow.com/a/28460399/4232337 This, of course, would be less interesting if you're looking to have the "snap" behavior that the ViewPager provides – NSimon Oct 10 '17 at 14:48

1 Answers1

3

You can use ViewPager for that. Having 100 fragments inside is totally fine because ViewPager will only load as much as you set using setOffscreenPageLimit(pageLimit). For instance, if you set pageLimit = 3, ViewPager will only initialize 3 (up to 6) neighbour fragments that are on the right/left side of your currently visible fragment. And while you're swiping through fragments, it will kill the fragments that are out of this limit, and load new ones. So, there will be no overkill.

Ugurcan Yildirim
  • 5,973
  • 3
  • 42
  • 73