当我删除一个项目,然后添加一个新的项目时,删除的项目的信息仍然保留

时间:2019-04-08 11:39:10

标签: android android-recyclerview

我使用回收站视图来添加和删除带有edittext的块, 但是当我删除一个块,然后添加一个新块时,被删除的块中的信息将返回到一个新块,但是我需要添加一个干净的块

 delete.setOnClickListener(v -> {
            int position = getAdapterPosition();
            try {
                connector.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, connector.size());
                notifyDataSetChanged();
            } catch (ArrayIndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        });

 add.setOnClickListener(v -> {
            int position = getAdapterPosition();
            try {
                connector.add(position + 1, "");
                notifyItemInserted(position + 1);
            } catch (ArrayIndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        });

ViewHolder已满:

public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView delete;
    TextInputEditText typeOfConnector;

    @SuppressLint("CutPasteId")
    public ViewHolder(View itemView) {
        super(itemView);
        delete = itemView.findViewById(R.id.iv_garbage);
        typeOfConnector = itemView.findViewById(R.id.type_of_connector_et);

        delete.setOnClickListener(v -> {
            int position = getAdapterPosition();
            try {
                connector.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, connector.size());
                notifyDataSetChanged();
            } catch (ArrayIndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        });

        add.setOnClickListener(v -> {
            int position = getAdapterPosition();
            try {
                connector.add(position + 1, "");
                notifyItemInserted(position + 1);
            } catch (ArrayIndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您不需要全部三个命令:

notifyItemRemoved(position);
notifyItemRangeChanged(position, connector.size());
notifyDataSetChanged();

对于您的用例:只需notifyItemRemoved(position);即可

现在,在bindViewHolder方法中,您需要将Edittext设置为连接器中相应的字符串。