简体   繁体   中英

Using the same Fragment in an Endless ViewPager

Looking for a bit of insight. I have a list of forum threads coming from an API which the user clicks on and it loads up a fragment with the posts in that thread.

What I want the user to do is be able to swipe between each thread while they're looking into it. Like how Gmail does it when the user looks at each email by swiping through.

I'm happy to answer any more questions. I couldn't find anything on here specific to what I'm looking for but I may be wrong.

Thank you

If i have understood your question properly, this should be the solution.

Lets say the fragment that displays the thread is called ThreadFragment . You can have an arraylist of this fragments in your FragmentPagerAdapter class.

private ArrayList<ThreadFragment> threadFragments = new ArrayList<>(size)

Where size is the number of threads you have. Create 'size' fragments in a loop and and it to the array list.

for(all the threads) {
    threadFragments.add(new ThreadFragment(data from your api));
}

implement the other functions of the FragmentPagerAdapter as follow:

@Override
public int getCount() {
   return threadFragments.size();
}

@Override 
public Fragment getItem(int pos) {
    return threadFragments.get(pos);
}

Suggestions for you to try: Instead of passing parameter in the Fragment's constructor, try to use Bundle. You can also have an abstract method in the fragment to get the data, and implement it in the FragmentPagerAdapter when you create the fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM