FragmentPagerAdapter无法刷新问题

1、原因:在FragmentPagerAdapter的instantiateItem()方法里,他会先去FragmentManager里面去查找有没有相关的fragment如果有就直接使用如果没有才会触发fragmentpageadapter的getItem()方法获取一个fragment。所以你更新fragments集合是没有作用的。

    @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;
    }

2、重写FragmentPagerAdapter的instantiateItem()方法,如果出现“Can not perform this action after onSaveInstanceState”问题,把commit() 改为 commitAllowingStateLoss()。

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //1.获取缓存的fragment
            Fragment fragment = (Fragment) super.instantiateItem(container, position);
            //2.得到其tag
            String tag = fragment.getTag();
            //3.如果这个fragment需要更新
            if (position == POSITION_TASK){
                FragmentTransaction transaction = fm.beginTransaction();
                //4.移除旧的fragment
                transaction.remove(fragment);
                //5.获取新的fragment
                fragment = fragments.get(POSITION_TASK);
                //6.添加新fragment时必须用前面获得的tag
                transaction.add(container.getId(),fragment,tag);
                transaction.attach(fragment);
                transaction.commit();
            }
            return fragment;
        }

3、重写FragmentPagerAdapter的getItemPosition()方法。

        @Override
        public int getItemPosition(Object object) {
        //需要更新的fragment必须返回POSITION_NONE,否则instantiateItem()不会被调用
            if (object instanceof Taskfragment){
                return POSITION_NONE;
            }
            return super.getItemPosition(object);
        }

你可能感兴趣的:(android)