I am using a ViewPager with FragmentStatePagerAdapter. My application requires me to add, remove and reorder the fragments like the user wants. I tried to implement this by overriding the getItem() and getItemPosition() functions.
My Method :
Before the user begins, I store the initial position of each fragment as it's ID and use the setID() function to give each fragment it's ID.
The user is taken to a different view where the user can add, remove and reorder the fragments as she/he wants.
I map the new and old positions of the fragments using a sparse array.
In the getItemPosition() function I use the fragment ID to get the corresponding new position in the sparse array or return position_none if the fragment was deleted.
I have set the offset to high enough value to make sure fragments are not deleted while using viewpager.
The Problem : The sparse array is giving correct new positions , I have verified. The problem comes when I add a new blank fragment. Most of the time they are not even created and getItem() is never called. They are only created if I delete and add fragments only at the end and then do not reorder the new fragments.
I am starting to think it's not even allowed to do such a thing in the FragmentStatePagerAdapter class. But wanted to ask just in case anyone has a solution.
Here is my code:
The adapter :
private class SlidePageAdapter extends FragmentStatePagerAdapter{
private boolean firstRun=true;
public SlidePageAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
SlideFragment slideFragment;
//On the first run no recycling of fragments happens.
//On every run after the first getitem is only used to create blank fragments as old fragments are always recycled or deleted
if(firstRun)
{ //Create a fragment for this position
slideFragment= new SlideFragment(position);
}
else
{
//Create a blank fragment
slideFragment= new SlideFragment(-1);
}
aliveFragments.append(position, slideFragment);
if(aliveFragments.size()==(numOfFragments))
firstRun=false;
slideFragment.setID(position);
return slideFragment;
}
@Override
public int getCount() {
return numOfFragments;
}
@Override
public int getItemPosition(Object object) {
SlideFragment fragment=(SlideFragment) object;
Integer newPosition=newPositions.get(fragment.getID());
if(newPosition!=null){
aliveFragments.append(newPosition, fragment);
fragment.setID(newPosition);
return newPosition;
}
else
{
return POSITION_NONE;
}
}
}
0 comments:
Post a Comment