FragmentStatePagerIssueExample icon indicating copy to clipboard operation
FragmentStatePagerIssueExample copied to clipboard

Additional check in "instantiateItem"

Open tingyik90 opened this issue 7 years ago • 0 comments

In instantiateItem, we need to add additional check to make sure the fragment retrieved from mFragments is correct.

String fragmentTag = getTag(position); 
if (mFragments.size() > position) {
    Fragment f = mFragments.get(position);
    if (f != null && TextUtils.equals(f.getTag(), fragmentTag)) {
        return f;
    }
}

This is because calling notifyDataSetChanged(), eventually calling getItemPosition(), does not remove the fragment at the end of list.

In my case, A(0), B(1), C(2) are initiated. When deleting B(1), I animate viewpager to move current item to C(2) first. This makes mFragments to be A-destroyed(0), B(1), C-currentItem(2), D-initiated(3).

I then call notifyDataSetChanged() and this return POSITION_NONE for B(1). This updates mFragments to be A-recalled(0), C-currentItem(1), D-reinserted(2), D-not deleted(3). So when I swipe right, a new fragment E(3) was not created. Fragment D-not deleted was recalled and it gave a black screen in viewpager.

tingyik90 avatar May 03 '18 18:05 tingyik90