Android: Removing And Adding Views To A Recyclerview Properly
Solution 1:
The idea behind RecyclerViews is that the view holder you provide in onCreateViewHolder()
may be reused for views of the same viewType
. This behavior is what makes RecyclerViews efficient - it is expensive to inflate views, and expensive to run findViewById
.
You did not override getItemViewType
so your RecyclerView only has one viewtype -- i.e. your ViewHolders are free to be recycled amongst each other as you scroll across many views, and delete/add views.
So what is happening in your code? When you delete view number two, its ViewHolder is recycled, and sent back to the recycler view pool. When you add view number 6, the recycler view uses the recycled view holder from number 2. Thus, onCreateViewHolder
is never called (because there was an extra view to recycle!). However, onBindViewHolder
is called. So add a method to update the data displayed by the ViewHolder:
publicvoidsetData(final int position) {
eventName.setText(String.format("", position));
theLayout.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
if (position == 1){
addItem("");
}else {
removeItem(position);
}
}
}
and call this method in onBindViewHolder:
@OverridepublicvoidonBindViewHolder(ViewHolder holder, int position) {
holder.setData(position);
}
Solution 2:
Try changing your removeItem(int position)
to
public void removeItem(int position) {
items.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, items.size());
}
It will most probably solve your issue
Post a Comment for "Android: Removing And Adding Views To A Recyclerview Properly"