RecyclerView的添加和删除

RecyclerView的添加和删除(单个item和批量的操作)
不多说直接上代码

先是RecyclerView的配置

mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mRecyclerView.setHasFixedSize(true);
mAdapter = new MyAdapter(this, mList, this);
mRecyclerView.setAdapter(mAdapter);

Adapter里面
添加单个item
position:要插入item的位置
element:插入的item值

public void addItem(int position, String element){
	if (position >= 0) {
		//给adapter里面的数据集合添加元素
		mList.add(position, element);
		//添加插入后的动画效果
		notifyItemInserted(position);
		//插入后,更新后面item的position
		notifyItemRangeChanged(position, mList.size() - position, "addItem");
	}
}

添加多个item
position:要插入items的位置
list:插入items的list集合

public void addItems(int position, List list){
	if (position >= 0){
		mList.addAll(position, list);
		notifyItemRangeInserted(position, list.size());
		notifyItemRangeChanged(position, mList.size() - position, "addItems");
	}
}

删除单个item
position:要删除的item的位置

public void removeItem(int position) {
	//这里加入position >= 0的条件是因为快速点击每个item后面的删除按钮时,会出现position = -1的情况,就会出现奔溃。
	if (position >= 0 && position < mList.size()) {
		mList.remove(position);
		notifyItemRemoved(position);
		//刷新删除后每个item的position
		notifyItemRangeChanged(position, mList.size() - position, "removeItem");
	}
}

删除多个items
list:要删除的item集合
positionStart:

public void removeItems(HashSet list, int positionStart) {
        boolean result = mList.removeAll(list);
        if (result) {
            notifyItemRangeRemoved(positionStart, list.size());
            notifyItemRangeChanged(positionStart, mList.size() - positionStart, "removeItems");
        } else {
            Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
        }
    }

当然adapter里面还有重新onBindViewHolder(MyHolderView holder, int position, List payloads)方法,来刷新item的数据。

@Override
public void onBindViewHolder(MyHolderView holder, int position, List payloads) {
	if (payloads.isEmpty()){
		onBindViewHolder(holder, position);
	}else{
		holder.text.setText(holder.getAdapterPosition());
	}
}
 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(android)