简体   繁体   English

在Endless ViewPager中使用相同的片段

[英]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. 我有一个来自用户单击的API的论坛主题列表,它加载了该主题中带有帖子的片段。

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. 就像Gmail在用户通过浏览查看每封电子邮件时的方式一样。

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 . 假设显示线程的片段称为ThreadFragment You can have an arraylist of this fragments in your FragmentPagerAdapter class. 您可以在FragmentPagerAdapter类中具有此片段的数组列表。

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

Where size is the number of threads you have. 其中size是您拥有的线程数。 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: 实现FragmentPagerAdapter的其他功能,如下所示:

@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. 尝试的建议:尝试使用Bundle,而不是在Fragment的构造函数中传递参数。 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. 您也可以在片段中使用抽象方法来获取数据,并在创建片段时在FragmentPagerAdapter中实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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