我正在调用一个返回json的api。我将json解析为对象的arraylist。我创建了一个类,用于从列表中随机选择一个元素并将其删除并在viewpager中显示。我有viewpager和pageradapter设置和asyncloader来创建数据集。我得到了以下的运行时异常。如果我改变了getCount()以返回一个静态数字,那么它就像我想要的那样工作,但它并没有达到我在下面列出的要求。
The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 14, found: 12 Pager id
我完全理解为什么会这样。以下代码就是原因。
随机元素类:此方法提供我想在viewpager中显示的随机对象,同时从列表中删除,所以我不再检索它。
public T spin() throws IllegalStateException, NullPointerException {
if (list == null)
throw new NullPointerException("A list has not been set.");
if (list.size() > 0) {
int i = rand.nextInt(list.size());
T b = list.remove(i);
return b;
} else {
throw new IllegalStateException("There are no more elements left. Please query more.") ;
}
}
这是我的内部Pageradapter类 - r 是randomelement类的对象:
private class RPagerAdapter extends PagerAdapter {
private Context context;
public RPagerAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return r.size();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ViewHolder mViewHolder = new ViewHolder(context);
mViewHolder.setItem(r.spin());
container.addView(mViewHolder);
return mViewHolder;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
我想要完成的是以下内容:
请告诉我是否有不同的方法可以实现上述内容或指向我使用右侧的android apis。
答案 0 :(得分:0)
调用PagerAdapter方法startUpdate(ViewGroup)表示 ViewPager的内容即将发生变化。一个或多个 调用instantiateItem(ViewGroup,int)和/或destroyItem(ViewGroup, 将跟随int,Object),并且将通过以下方式发出更新结束信号 调用finishUpdate(ViewGroup)。
因此,您只应在finishUpdate(ViewGroup)
忘记你的整个旋转结构,试试这样的东西,仅伪代码:
private class RPagerAdapter extends PagerAdapter {
private Context context;
private List<T> items;
public RPagerAdapter(Context context, List<T> items) {
this.context = context;
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ViewHolder mViewHolder = new ViewHolder(context);
mViewHolder.setItem(items.get(position));
container.addView(mViewHolder);
container.setTag(String.valueOf(position));
return mViewHolder;
}
@Override
public void finishUpdate(ViewGroup container) {
int position = Integer.parseInt(container.getTag());
//remove all items before position
//add items at the end if you want
notifyDataSetChanged();
viewPager.setCurrentItem(0, false);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}