FragmentPagerAdapter is very useful and easy-to-use.
But, there is one point to keep it mind when using it.
See below codes from FragmentPagerAdapter.java

    @Override
    public Object instantiateItem(View container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        // Do we already have this fragment?
        String name = makeFragmentName(container.getId(), position);
        Fragment fragment = mFragmentManager.findFragmentByTag(name);
        if (fragment != null) {
            if (DEBUG) Log.v(TAG, "Attaching item #" + position + ": f=" + fragment);
            mCurTransaction.attach(fragment);
        } else {
            fragment = getItem(position);
            if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
            mCurTransaction.add(container.getId(), fragment,
                    makeFragmentName(container.getId(), position));
        }
        if (fragment != mCurrentPrimaryItem) {
            fragment.setMenuVisibility(false);
            fragment.setStartDeferred(true);
        }

        return fragment;
    }

Usually, FragmentPagerAdapter is used with ViewPager. In this case, variable container is reference of ViewPager.

Developer who are familiar with normal AdapterView, may try to change FragmentPagerAdapter by using setAdapter interface of ViewPager without doing something else to ViewPager.

But, in this case, as you can see from above code, instantiateItem function reuses previous Fragment instance because even if FragmentPagerAdapter is changed, ViewPager is same. So, fragment name getting from makeFragmentName function returns same value.

And that is NOT expected result at normal AdatperView.


+ Recent posts