Reputation: 2145
public class FolioPageFragmentAdapter extends FragmentStatePagerAdapter{
private List<SpineReference> mSpineReferences;
private Book mBook;
private String mEpubFileName;
private boolean mIsSmilAvailable;
private FolioPageFragment mFolioPageFragment;
public FolioPageFragmentAdapter(FragmentManager fm, List<SpineReference> spineReferences,
Book book, String epubFilename, boolean isSmilAvilable) {
super(fm);
this.mSpineReferences = spineReferences;
this.mBook = book;
this.mEpubFileName = epubFilename;
this.mIsSmilAvailable = isSmilAvilable;
}
@Override
public Fragment getItem(int position) {
mFolioPageFragment = FolioPageFragment.newInstance(position, mBook, mEpubFileName, mIsSmilAvailable);
return mFolioPageFragment;
}
@Override
public int getCount() {
return mSpineReferences.size();
}
public FolioPageFragment getCurrentFragment(){
return mFolioPageFragment;
}
}
It doesn't give me the correct current fragment.
Is there any way so that i can get the current Fragment. I have changed the FragmentPagerAdapter to FragmentStatePagerAdapter. The below method doesn't give the current Fragment. Evert time the instance is created i'm storing it in the global variable still it does not work for me.
private Fragment getFragment(int pos) {
return getSupportFragmentManager().
findFragmentByTag("android:switcher:" + R.id.folioPageViewPager + ":" + (pos));
}
Upvotes: 1
Views: 76
Reputation: 10175
The problem is that the FragmentStatePagerAdapter
has a different loading that you've expected to have.
When it's loaded and set a position
it will load: the fragment at position - 1
, fragment at position
, fragment at position + 1
. So in your case the global variable will hold the fragment at position+1
.
When you swipe, the last loaded fragment will be position - 1
or position + 1
depending on the scroll direction.
What you should do, is to keep a HashMap
with the position & the fragment for that position. Then based on the current position you'll query the HashMap
and return the fragment.
You should also detect swipe/page changes and remove destroyed fragments from the HasMap
so it won't keep reference to them, thus memory issues.
Upvotes: 1
Reputation: 2434
This probably don't work, because getItem() can return next/previous fragment. Try to make array of fragments, store there created fragments and retrieve from array current.
Upvotes: 1