FragmentPagerAdapter踩坑

FragmentPagerAdapter

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);
  • 该方法相当于初始化,应该称为instantiateItem。
    创建fragment用此方法。
 @SuppressWarnings("ReferenceEquality")
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        final long itemId = getItemId(position);

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

        return fragment;
    }
  • 该方法相当于获取,应该称为getItem。
    获取适配器获取已创建fragment实例应该用此方法。

你可能感兴趣的:(FragmentPagerAdapter踩坑)