24

我相信 FragmentStatePagerAdapter 在getItemPosition(Object object)以重新排序页面为目的进行覆盖时行为不正确。

下面是一个简单的例子。在初始状态下,页面的顺序是{A, B, C}。调用 后toggleState(),页面顺序变为 {A, C, B}。通过覆盖getItemPosition(Object object),我们确保正在查看的当前页面(A、B 或 C)不会改变。

public static class TestPagerAdapter extends FragmentStatePagerAdapter {
    private boolean mState = true;

    public TestPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public int getCount() {
        return 3;
    }

    private void toggleState() {
        mState = !mState;
        notifyDataSetChanged();
    }

    private String getLabel(int position) {
        switch (position) {
            case 0:
                return "A";
            case 1:
                return mState ? "B" : "C";
            default:
                return mState ? "C" : "B";
        }
    }

    @Override
    public int getItemPosition(Object object) {
        String label = ((TestFragment) object).getLabel();
        if (label.equals("A")) {
            return 0;
        } else if (label.equals("B")) {
            return mState ? 1 : 2;
        } else {
            return mState ? 2 : 1;
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return getLabel(position);
    }

    @Override
    public Fragment getItem(int position) {
        return TestFragment.newInstance(getLabel(position));
    }
}

我遇到了两种似乎不正确的单独行为。

  1. 如果我立即调用toggleState()(在查看页面 A 时,在滑动到任何其他页面之前),应用程序就会崩溃。

    java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
      at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
      at java.util.ArrayList.set(ArrayList.java:477)
      at android.support.v4.app.FragmentStatePagerAdapter.destroyItem(FragmentStatePagerAdapter.java:136)
      at android.support.v4.view.ViewPager.populate(ViewPager.java:867)
      at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:469)
      at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:441)
      at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:766)
      at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2519)
      at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
      at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
      at com.ugglynoodle.test.testfragmentstatepageradapter.MainActivity$TestPagerAdapter.toggleState(MainActivity.java:55)
      ...
    

    查看 的来源FragmentStatePagerAdapter,这将通过在调用第 136 行mFragments之前首先检查的大小(如第 113-115 行)来解决。set()

  2. 如果我首先滑动到页面 B,然后getItem(2)调用,页面 C 被创建,并且mFragments现在的大小为 3(这将防止上述崩溃立即发生)。然后我滑回页面 A,页面 C 被破坏,因为它应该是(因为它是 2 页,并且我使用默认的屏幕外页面限制 1)。现在,我打电话给toggleState(). 页面 B 现已销毁。但是,不会重新创建页面 C!这意味着,当我现在向右滑动时,我得到一个空白页面。

首先,很高兴知道我是否正确并且这些实际上是错误,或者我是否做错了什么。如果它们是错误,任何人都可以提出解决方法(除了自己调试和重建支持库)吗?肯定有人已经getItemPosition(Object object)成功覆盖(除了将所有内容设置为POSITION_NONE)?

我正在使用支持库的当前版本 (10)。

4

4 回答 4

37

查看 FragmentStatePagerAdapter 的来源,我确切地知道出了什么问题。mFragmentsFragmentStatePagerAdapter 在 ArrayLists:和中缓存片段和保存的状态mSavedState。但是当片段被重新排序时,没有重新排序mFragmentsand元素的机制mSavedState。因此,适配器会向寻呼机提供错误的片段。

我为此提交了一个问题,并将一个固定的实现(NewFragmentStatePagerAdapter.java)附加到该问题上。在修复中,我getItemId()向 FragmentStatePagerAdapter 添加了一个函数。(这反映了 FragmentPagerAdapter 中的重新排序实现。)始终按适配器位置存储 itemId 的数组。然后,在 中notifyDataSetChanged(),适配器检查 itemIds 数组是否已更改。如果有,则相应mFragmentsmSavedState重新排序。进一步的修改可以在destroyItem()saveState()中找到restoreState()

要使用这个类,getItemPosition()并且getItemId()必须与getItem().

于 2012-09-29T08:16:05.167 回答
1

对我来说是一个问题的答案之一。答案 #20 #21。链接到解决方案https://gist.github.com/ypresto/8c13cb88a0973d071a64。最佳解决方案,适用于更新页面和重新排序。只有在此解决方案中,适配器在销毁项目时(在方法 destroyItem 中)没有抛出 IndexOutOfBoundsExeption,这是其他解决方案的已知错误。

于 2016-10-11T20:27:56.083 回答
0

我在 Kotlin 中重新实现了现有的解决方案,以便它允许您返回 aString而不是 along作为项目 ID。您可以在此处或下方找到它:

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.view.View
import android.view.ViewGroup
import java.util.HashSet
import java.util.LinkedHashMap

/**
 * A PagerAdapter that can withstand item reordering. See
 * https://issuetracker.google.com/issues/36956111.
 *
 * @see android.support.v4.app.FragmentStatePagerAdapter
 */
abstract class MovableFragmentStatePagerAdapter(
        private val manager: FragmentManager
) : NullablePagerAdapter() {
    private var currentTransaction: FragmentTransaction? = null
    private var currentPrimaryItem: Fragment? = null

    private val savedStates = LinkedHashMap<String, Fragment.SavedState>()
    private val fragmentsToItemIds = LinkedHashMap<Fragment, String>()
    private val itemIdsToFragments = LinkedHashMap<String, Fragment>()
    private val unusedRestoredFragments = HashSet<Fragment>()

    /** @see android.support.v4.app.FragmentStatePagerAdapter.getItem */
    abstract fun getItem(position: Int): Fragment

    /**
     * @return a unique identifier for the item at the given position.
     */
    abstract fun getItemId(position: Int): String

    /** @see android.support.v4.app.FragmentStatePagerAdapter.startUpdate */
    override fun startUpdate(container: ViewGroup) {
        check(container.id != View.NO_ID) {
            "ViewPager with adapter $this requires a view id."
        }
    }

    /** @see android.support.v4.app.FragmentStatePagerAdapter.instantiateItem */
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val itemId = getItemId(position)

        val f = itemIdsToFragments[itemId]
        if (f != null) {
            unusedRestoredFragments.remove(f)
            return f
        }

        if (currentTransaction == null) {
            // We commit the transaction later
            @SuppressLint("CommitTransaction")
            currentTransaction = manager.beginTransaction()
        }

        val fragment = getItem(position)
        fragmentsToItemIds.put(fragment, itemId)
        itemIdsToFragments.put(itemId, fragment)

        val fss = savedStates[itemId]
        if (fss != null) {
            fragment.setInitialSavedState(fss)
        }
        fragment.setMenuVisibility(false)
        fragment.userVisibleHint = false

        currentTransaction!!.add(container.id, fragment)

        return fragment
    }

    /** @see android.support.v4.app.FragmentStatePagerAdapter.destroyItem */
    override fun destroyItem(container: ViewGroup, position: Int, fragment: Any) {
        (fragment as Fragment).destroy()
    }

    /** @see android.support.v4.app.FragmentStatePagerAdapter.setPrimaryItem */
    override fun setPrimaryItem(container: ViewGroup, position: Int, fragment: Any?) {
        fragment as Fragment?
        if (fragment !== currentPrimaryItem) {
            currentPrimaryItem?.let {
                it.setMenuVisibility(false)
                it.userVisibleHint = false
            }

            fragment?.setMenuVisibility(true)
            fragment?.userVisibleHint = true
            currentPrimaryItem = fragment
        }
    }

    /** @see android.support.v4.app.FragmentStatePagerAdapter.finishUpdate */
    override fun finishUpdate(container: ViewGroup) {
        if (!unusedRestoredFragments.isEmpty()) {
            for (fragment in unusedRestoredFragments) fragment.destroy()
            unusedRestoredFragments.clear()
        }

        currentTransaction?.let {
            it.commitAllowingStateLoss()
            currentTransaction = null
            manager.executePendingTransactions()
        }
    }

    /** @see android.support.v4.app.FragmentStatePagerAdapter.isViewFromObject */
    override fun isViewFromObject(view: View, fragment: Any): Boolean =
            (fragment as Fragment).view === view

    /** @see android.support.v4.app.FragmentStatePagerAdapter.saveState */
    override fun saveState(): Parcelable? = Bundle().apply {
        putStringArrayList(KEY_FRAGMENT_IDS, ArrayList<String>(savedStates.keys))
        putParcelableArrayList(
                KEY_FRAGMENT_STATES,
                ArrayList<Fragment.SavedState>(savedStates.values)
        )

        for ((f, id) in fragmentsToItemIds.entries) {
            if (f.isAdded) {
                manager.putFragment(this, "$KEY_FRAGMENT_STATE$id", f)
            }
        }
    }

    /** @see android.support.v4.app.FragmentStatePagerAdapter.restoreState */
    override fun restoreState(state: Parcelable?, loader: ClassLoader?) {
        if ((state as Bundle?)?.apply { classLoader = loader }?.isEmpty == false) {
            state!!

            fragmentsToItemIds.clear()
            itemIdsToFragments.clear()
            unusedRestoredFragments.clear()
            savedStates.clear()

            val fragmentIds: List<String> = state.getStringArrayList(KEY_FRAGMENT_IDS)
            val fragmentStates: List<Fragment.SavedState> =
                    state.getParcelableArrayList(KEY_FRAGMENT_STATES)

            for ((index, id) in fragmentIds.withIndex()) {
                savedStates.put(id, fragmentStates[index])
            }

            for (key: String in state.keySet()) {
                if (key.startsWith(KEY_FRAGMENT_STATE)) {
                    val itemId = key.substring(KEY_FRAGMENT_STATE.length)

                    manager.getFragment(state, key)?.let {
                        it.setMenuVisibility(false)
                        fragmentsToItemIds.put(it, itemId)
                        itemIdsToFragments.put(itemId, it)
                    }
                }
            }

            unusedRestoredFragments.addAll(fragmentsToItemIds.keys)
        }
    }

    private fun Fragment.destroy() {
        if (currentTransaction == null) {
            // We commit the transaction later
            @SuppressLint("CommitTransaction")
            currentTransaction = manager.beginTransaction()
        }

        val itemId = fragmentsToItemIds.remove(this)
        itemIdsToFragments.remove(itemId)
        if (itemId != null) {
            savedStates.put(itemId, manager.saveFragmentInstanceState(this))
        }

        currentTransaction!!.remove(this)
    }

    private companion object {
        const val KEY_FRAGMENT_IDS = "fragment_keys_"
        const val KEY_FRAGMENT_STATES = "fragment_states_"
        const val KEY_FRAGMENT_STATE = "fragment_state_"
    }
}

还有 Java 部分:

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.view.ViewGroup;

/**
 * A PagerAdapter whose {@link #setPrimaryItem} is overridden with proper nullability annotations.
 */
public abstract class NullablePagerAdapter extends PagerAdapter {
    @Override
    public void setPrimaryItem(@NonNull ViewGroup container,
                               int position,
                               @Nullable Object object) {
        // `object` is actually nullable. It's even in the dang source code which is hilariously
        // ridiculous:
        // `mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null);`
    }
}
于 2017-11-12T04:14:58.133 回答
0

好的,我找到了解决方案。这修复了 viewpager 片段的重新排序问题,以防您动态创建/修改新选项卡。

使用此类代替 FragmentStatePagerAdapter.java

package android.support.v4.app;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public abstract class NewFragmentStatePagerAdapter extends PagerAdapter {
    private static final String TAG = "FragmentStatePagerAdapt";
    private static final boolean DEBUG = false;

    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;

    private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
    private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
    private Fragment mCurrentPrimaryItem = null;

    public NewFragmentStatePagerAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    @Override
    public void startUpdate(ViewGroup container) {
        if (container.getId() == View.NO_ID) {
            throw new IllegalStateException("ViewPager with adapter " + this
                    + " requires a view id");
        }
    }
    public void destroyItemState(int position) {
        mFragments.remove(position);
        mSavedState.remove(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // If we already have this item instantiated, there is nothing
        // to do.  This can happen when we are restoring the entire pager
        // from its saved state, where the fragment manager has already
        // taken care of restoring the fragments we previously had instantiated.
        if (mFragments.size() > position) {
            Fragment f = mFragments.get(position);
            if (f != null) {
                return f;
            }
        }

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        Fragment fragment = getItem(position);
        if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
        if (mSavedState.size() > position) {
            Fragment.SavedState fss = mSavedState.get(position);
            if (fss != null) {
                fragment.setInitialSavedState(fss);
            }
        }
        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
        mFragments.set(position, fragment);
        mCurTransaction.add(container.getId(), fragment);

        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
                + " v=" + ((Fragment)object).getView());
        while (mSavedState.size() <= position) {
            mSavedState.add(null);
        }
        mSavedState.set(position, fragment.isAdded()
                ? mFragmentManager.saveFragmentInstanceState(fragment) : null);
        mFragments.set(position, null);

        mCurTransaction.remove(fragment);
    }

    @Override
    @SuppressWarnings("ReferenceEquality")
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment)object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(true);
                fragment.setUserVisibleHint(true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitNowAllowingStateLoss();
            mCurTransaction = null;
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment)object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        Bundle state = null;
        if (mSavedState.size() > 0) {
            state = new Bundle();
            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
            mSavedState.toArray(fss);
            state.putParcelableArray("states", fss);
        }
        for (int i=0; i<mFragments.size(); i++) {
            Fragment f = mFragments.get(i);
            if (f != null && f.isAdded()) {
                if (state == null) {
                    state = new Bundle();
                }
                String key = "f" + i;
                mFragmentManager.putFragment(state, key, f);
            }
        }
        return state;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        if (state != null) {
            Bundle bundle = (Bundle)state;
            bundle.setClassLoader(loader);
            Parcelable[] fss = bundle.getParcelableArray("states");
            mSavedState.clear();
            mFragments.clear();
            if (fss != null) {
                for (int i=0; i<fss.length; i++) {
                    mSavedState.add((Fragment.SavedState)fss[i]);
                }
            }
            Iterable<String> keys = bundle.keySet();
            for (String key: keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    Fragment f = mFragmentManager.getFragment(bundle, key);
                    if (f != null) {
                        while (mFragments.size() <= index) {
                            mFragments.add(null);
                        }
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
        }
    }
}

并使用它来覆盖该方法

 @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            if (getItemPosition(object) == POSITION_NONE) {
                destroyItemState(position);
            }
        }

来源:https ://issuetracker.google.com/issues/36956111

于 2019-06-24T09:51:44.113 回答