gpt4 book ai didi

android - ViewPager、FragmentStatePagerAdapter 和无限滚动

转载 作者:行者123 更新时间:2023-11-29 17:52:41 27 4
gpt4 key购买 nike

我想要实现的目标:

带有 ViewPager 的 Activity,显示适配器中对象列表的 fragment (FragmentStatePagerAdapter)。

最初,Activity 将 SQLite 数据库中的 N(比方说 5)个对象加载到适配器中。这些对象是随机选择的。

当用户到达列表末尾时, Activity 应从数据库中加载 M(设 M 为 3)个对象,将它们添加到适配器并调用 notifyDataSetChanged()。添加它们时,我会检查新对象是否已存在于列表中,如果存在,则删除先前存在的对象并将加载的对象添加到列表的尾部。

因此,我正在尝试实现类似无限滚动 ViewPager 的东西(不是“循环”ViewPager,因为我希望不断获取新对象,而不是返回到列表)。

我有一些工作代码,并包含了一个我正在遵循的模式的示例。但是,我一直收到此异常并且不知道为什么:

IllegalStateException: Fragment MyObjectFragment{id...} is not currently in the FragmentManager
at android.app.FragmentManagerImpl.saveFragmentInstanceState(FragmentManager.java:553)
at android.support.v13.app.FragmentStatePagerAdapter.destroyItem(FragmentStatePagerAdapter.java:140)
at android.support.v4.ViewPager.populate(ViewPager.java:1002)
...

代码示例:

Activity :

public class MyActivitty extends FragmentActivity {

public MyPagerAdapter adapter;
public ViewPager pager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.my_acyivity_layout);
pager = (ViewPager) findViewById(R.id.viewPager);

ArrayList<MyObject> myObjects = new ArrayList<MyObject>();

// loadInitialObjectsFromDB(int N) goes to SQLite DB and loads the N first objects to show on the ViewPager...
myObjects = loadInitialObjectsFromDB(5);

// Adapter will use the previously fetched objects
adapter = new MyPagerAdapter(this, getFragmentManager(), myObjects);

pager.setAdapter(adapter);
pager.setOffscreenPageLimit(2);

// (...)
}

// (...)
}

PagerAdapter:

public class MyPagerAdapter extends FragmentStatePagerAdapter implements
ViewPager.OnPageChangeListener {

private MyActivity context;
private ArrayList<MyObject> objectList;
private int currentPosition = 0;

// (...)

public MyPagerAdapter(MyActivity context, FragmentManager fragmentManager, ArrayList<MyObject> objects)
{
super(fragmentManager);
this.context = context;
this.objectList = objects;
}

@Override
public Fragment getItem(int position)
{
MyObject object = objectList.get(position);
return MyObjectFragment.newInstance(position, object);
}

@Override
public int getItemPosition(Object object){
MyObjectFragment frag = (MyObjectFragment) object;
MyObject object = frag.getMyObject();

for(int i = 0; i < objectList.size(); i++)
{
if(objectList.get(i).getId() == object.getId())
{
return i;
}
}

return PagerAdapter.POSITION_NONE;
}

@Override
public int getCount()
{
return objectList.size();
}

@Override
public void onPageSelected(int position)
{
currentPosition = position;
}

// (...)

}


@Override
public void onPageScrollStateChanged(int state)
{
switch(state)
{
case ViewPager.SCROLL_STATE_DRAGGING:
// (...)
break;

case ViewPager.SCROLL_STATE_IDLE:
// if we are reaching the "end" of the list (while scrolling to the right), load more objects
if(currentPosition <= position && position >= answerList.size()-1)
{
// Function in MyActivity that fetches N more objects.
// and adds them to this adapter's ArrayList<MyObject> objectList
// it checks for duplicates so that if the fetched object was already in the back of the list, it is shown again
context.getMoreObjects(3);
notifyDataSetChanged();
}
getMoreQuestions(currentPosition);



case ViewPager.SCROLL_STATE_SETTLING:
break;
}

}

我的 fragment :

public class MyObjectFragment extends Fragment {

// Object to represent
private MyObject object;

public static Fragment newInstance(MyActivity context,
int position, MyObject object) {

MyObjectFragment frag = new MyObjectFragment();

Bundle args = new Bundle();
args.putParcelable("Object", object);
frag.setArguments(args);

return frag;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

this.currentInflater = inflater;

final View rootView = inflater.inflate(
R.layout.fragment_my_object, container, false);

// get object from Bundle, set UI, events, etc...

}

// (...)

}

知道为什么我会得到这个Exception吗?看起来 FragmentStatePagerAdapter 正试图销毁一个不再存在的项目,但我不明白为什么。

编辑 1:

如果我评论我的 @Override getItemPosition(Object object),我就不会再得到异常。但是,我需要重写 getItemPosition,因为有一个用例,用户删除当前显示的对象导致它从适配器的数组中消失并强制 getItemPosition 返回POSITION_NONE 如果项目不再存在。

编辑 2:

现在我知道只有当我从适配器的 objectList 中删除项目时才会发生此异常。我在两种情况下从 objectList 中删除了 MyObject 实例:

  • getMoreObjects() 添加从数据库中提取一个已经在 objectList 中的对象时,我将其删除并重新添加到头部的名单。我这样做是为了避免在 objectList 中出现具有相同 ID 的对象,因为 getItemPosition() 使用它们的 ID 来了解它们是否存在以及它们的位置。

  • 在返回之前,getMoreObjects() 从列表中移除前 N 个对象。我知道 FragmentStatePagerAdapter 已经通过只保留一些对象的内存 fragment 来节省内存,但我仍然想避免过多地增加我的 objectList 。现在,我对这行进行了评论,因为它不是那么重要。

最佳答案

this question 的帮助下解决了它本身指向 this issue .

FragmentStatePagerAdapter 在两个 ArrayLists 中缓存 fragment 及其保存状态:mFragmentsmSavedState。但是,当 fragment 的顺序发生变化时(在我的情况下可能会发生),没有机制可以对 mFragmentsmSavedState 的元素进行重新排序。因此,适配器将向寻呼机提供错误的 fragment 。

我修改了其中提供的代码,并将导入从 app.support.v4.Fragment 更改为 android.app.Fragment

public abstract class MyFragmentStatePagerAdapter extends PagerAdapter {
private static final String TAG = "FragmentStatePagerAdapter";
private static final boolean DEBUG = true;

private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;

private long[] mItemIds = new long[] {};
private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
private Fragment mCurrentPrimaryItem = null;

public MyFragmentStatePagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
mItemIds = new long[getCount()];
for (int i = 0; i < mItemIds.length; i++) {
mItemIds[i] = getItemId(i);
}
}

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

/**
* Return a unique identifier for the item at the given position.
*/
public int getItemId(int position) {
return position;
}

@Override
public void notifyDataSetChanged() {
long[] newItemIds = new long[getCount()];
for (int i = 0; i < newItemIds.length; i++) {
newItemIds[i] = getItemId(i);
}

if (!Arrays.equals(mItemIds, newItemIds)) {
ArrayList<Fragment.SavedState> newSavedState = new ArrayList<Fragment.SavedState>();
ArrayList<Fragment> newFragments = new ArrayList<Fragment>();

for (int oldPosition = 0; oldPosition < mItemIds.length; oldPosition++) {
int newPosition = POSITION_NONE;
for (int i = 0; i < newItemIds.length; i++) {
if (mItemIds[oldPosition] == newItemIds[i]) {
newPosition = i;
break;
}
}
if (newPosition >= 0) {
if (oldPosition < mSavedState.size()) {
Fragment.SavedState savedState = mSavedState.get(oldPosition);
if (savedState != null) {
while (newSavedState.size() <= newPosition) {
newSavedState.add(null);
}
newSavedState.set(newPosition, savedState);
}
}
if (oldPosition < mFragments.size()) {
Fragment fragment = mFragments.get(oldPosition);
if (fragment != null) {
while (newFragments.size() <= newPosition) {
newFragments.add(null);
}
newFragments.set(newPosition, fragment);
}
}
}
}

mItemIds = newItemIds;
mSavedState = newSavedState;
mFragments = newFragments;
}

super.notifyDataSetChanged();
}

@Override
public void startUpdate(ViewGroup container) {
}

@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);
mFragments.set(position, fragment);
mCurTransaction.add(container.getId(), fragment);

return fragment;
}

public void destroyItemState(int position) {
mFragments.remove(position);
mSavedState.remove(position);
}

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

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

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

mCurTransaction.remove(fragment);
}

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

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

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

@Override
public Parcelable saveState() {
Bundle state = new Bundle();
if (mItemIds.length > 0) {
state.putLongArray("itemids", mItemIds);
}
if (mSavedState.size() > 0) {
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) {
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);
mItemIds = bundle.getLongArray("itemids");
if (mItemIds == null) {
mItemIds = new long[] {};
}
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);
}
}
}
}
}
}

原始代码归功于用户 @UgglyNoodle .

然后,我没有使用 FragmentStatePagerAdapter,而是使用上面的 MyFragmentStatePagerAdapter 并覆盖 getItemPosition()getItemId()getItem() 一致。

关于android - ViewPager、FragmentStatePagerAdapter 和无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21877816/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com