Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Update:</strong> The problem that you described in comment is real, I missed it in first testing. After analyzing the source code of <code>FragmentPagerAdapter</code> I realized that all we need to do is to <strong>Override <code>getItemId()</code></strong> in a way that it won't return same id for different fragment items. E.g. current default implementation would just return position as an id for fragment which won't work for this case:</p> <pre><code> public long getItemId(int position) { return position; } </code></pre> <p>I am updating this answer, please have a look. As before I have tested this code and the problem you described is not happening now.</p> <hr> <p>Only thing you need is <strong>not</strong> to keep reference of fragments by yourself in <code>List</code>, This is done for you by <code>FragmentPagerAdapter</code>. And as far as I know its not a good practise either. And also even if you return <code>POSITION_NONE</code> from <code>getItemPosition()</code> as suggested by other answer(s), you will end up with Exception </p> <blockquote> <p>Caused by: java.lang.IllegalStateException: Can't change tag of fragment.</p> </blockquote> <p>This is because you are trying to reposition alive <code>Fragment</code>s in your <code>List</code> by adding a fragment at 0th index (which causes other fragments to reposition) and <code>ViewPager</code> assigns tags based on position.</p> <p>Keeping all this in mind, here is a tested and <strong>working</strong> modified adapter:</p> <pre><code>public class PagerAdapter extends FragmentPagerAdapter { public static class FragmentInfo { public String classz; public ImageFileObject imageFile; public static long IDS; public long id; public FragmentInfo(){ id = IDS++; } } private final List&lt;FragmentInfo&gt; fragments; private Context context; public PagerAdapter(FragmentManager fm, List&lt;FragmentInfo&gt; fragments, Context context) { super(fm); this.fragments = fragments; this.context = context; } @Override public Fragment getItem(int index) { FragmentInfo info = fragments.get(index); ImageViewFragment frag = (ImageViewFragment) Fragment.instantiate( context, info.classz, /* null arguments*/ null); frag.setImage(info.imageFile); return frag; } @Override public long getItemId(int position) { return fragments.get(position).id; } @Override public int getCount() { return fragments.size(); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } public void add() { FragmentInfo f = new FragmentInfo(); f.classz = ImageViewFragment.class.getName(); fragments.add(0, f); notifyDataSetChanged(); } } </code></pre> <p>Please change your code accordingly.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload