Android notifyItemInserted()复制列表项

Android notifyItemInserted()复制列表项,android,android-recyclerview,Android,Android Recyclerview,我有一个要求,我应该下载的广告项目,同时滚动和更新列表。由于调用notifyDataSetchManaged()会重置所有内容,因此我正在调用notifyItemInserted(position)。但是,调用此函数会复制列表中的项目。我发现列表中没有重复的项目。但是在调用notifyItemInserted之后,它复制了该项。我不知道如何解决这个问题。这就是我正在做的: mNewsList.add(mPreviousAdPosition, newsItem); mAdapter.notifyI

我有一个要求,我应该下载的广告项目,同时滚动和更新列表。由于调用notifyDataSetchManaged()会重置所有内容,因此我正在调用
notifyItemInserted(position)
。但是,调用此函数会复制列表中的项目。我发现列表中没有重复的项目。但是在调用
notifyItemInserted
之后,它复制了该项。我不知道如何解决这个问题。这就是我正在做的:

mNewsList.add(mPreviousAdPosition, newsItem);
mAdapter.notifyItemInserted(mPreviousAdPosition);

如果我打电话,它工作正常,没有重复的项目。但我不想重新创建列表项。问题是什么

您应该将该项添加到列表的末尾

mNewsList.add(newsItem);
然后像这样通知

mAdapter.notifyItemInserted(mNewsList.size()-1);

您的代码应该这样编写:

  public class RecyclerViewAdapter extends RecyclerView.Adapter{

   ...

   public void addData(int position, Item newsItem) {

        mNewsList.add(position, newsItem);

        notifyItemInserted(position);

   }

   ...

 }

然后您需要调用fun
addData

您可以将对象添加到数组的末尾,每个对象都有一个位置,需要在回收器视图中显示。在调用
notifyItemInserted(position)
之前,根据位置对该数组进行排序。通过这种方式,只会绘制所需的数据。我最近采用了这种方法,在“回收者”视图中添加了动态部分,效果非常好。

创建一个临时列表并添加项目,如下所述:

List<YourModel> mTmpList = new ArrayList<YourMdel>();

//add items (from 0 -> mPreviousAdPosition) to mTmpList;
for(int i=0; i<mPreviousAdPosition; i++) {
    mTmpList.add(mNewsList.get(i));
}

//add item at mPreviousAdPosition
mTmpList.add(newsItem);

//add remaining items and set i<=mNewsList.size() because we ha
for(int i=mPreviousAdPosition; i<=mNewsList.size(); i++) {
    mTmpList.add(mNewsList.get(i - 1)); //because we have added item at mPreviousAdPosition;
}

mNewsList = mTmpList;
mAdapter.notifyDataSetChanged();
List mTmpList=new ArrayList();
//将项目(从0->MPPreviousAdPosition)添加到mTmpList;

对于(int i=0;i我在完全相同的用例中遇到了相同的问题,解决方案是:

在适配器中实现此方法:

@Override
public long getItemId(int position) {
    //Return the stable ID for the item at position
    return items.get(position).getId();
}
//Indicates whether each item in the data set can be represented with a unique identifier
setHasStableIds(true);
在适配器的构造函数中调用此方法:

@Override
public long getItemId(int position) {
    //Return the stable ID for the item at position
    return items.get(position).getId();
}
//Indicates whether each item in the data set can be represented with a unique identifier
setHasStableIds(true);

这里什么是previousAdPosition?previousAdPosition取自提要。我们在此位置插入广告mnewslist.add(MPPreviousAdPosition,newsItem);mAdapter.notifyItemInserted(MPPreviousAdPosition);您将这些行放在何处?下载广告后,我会在列表中插入广告项,然后通知适配器,但我想在两者之间添加该项?这不适用于此类情况?在代码中,在调用notifyItemInserted.Ex-yourlistview.removeViewAt(MPPreviousAdPosition)之前删除视图;但是我有一个很大的列表,我想要列表中的所有项目。因此,插入广告的项目必须位于插入项目位置的下方。