我有一个arraylist并使用ImageButton从列表中删除项目。如果我从同一位置删除3个项目,则应用程序会因IndexOutOfBoundsException崩溃。在删除之前的项目之后,我无法确定如何更改项目的数组位置。
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
ExRow expense = expenseList.get(position);
holder.title.setText(expense.getTitle());
holder.amount.setText(expense.getAmount());
mRemoveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Remove the item on remove/button click
expenseList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, expenseList.size());
}
});
}
答案 0 :(得分:2)
有很多可能的解决方案。
根据我的说法,这个是理想的
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
ExRow expense = expenseList.get(holder.getAdapterPosition());
holder.title.setText(expense.getTitle());
holder.amount.setText(expense.getAmount());
mRemoveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Remove the item on remove/button click
int adapterPosition = holder.getAdapterPosition();
expenseList.remove(adapterPosition);
notifyItemRemoved(adapterPosition);
notifyDatasetChanged();
}
});
}
答案 1 :(得分:1)
在ArrayList
中,当您从索引中删除元素时,之后元素的索引将向左移动。一个例子:
Index | Value
0 A
1 B
2 C
3 D
从数组中删除索引2时,结果如下:
Index | Value
0 A
1 B
2 D
所以我的猜测是:您要从列表中删除索引position
,在某些时候,position
只是高于列表中元素的数量。
更新: 以下解决方案的一些灵感。如果不了解用例,很难找到一个好的解决方案。
public void onClick(View view) {
// Remove the item on remove/button click
if(position >= expenseList.size()) return;
expenseList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, expenseList.size());
}
或者:
public void onClick(View view) {
// Remove the item on remove/button click
if(expenseList.size() == 0) return;
if(position >= expenseList.size()) {
position = expenseList.size() -1;
}
expenseList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, expenseList.size());
}
等等。
答案 2 :(得分:0)
删除此行 notifyItemRangeChanged(position,expenseList.size());
notifyItemRemoved(位置);这足以从列表中删除项目。
答案 3 :(得分:0)
让你的模型最终并用它来确定位置。
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final ExRow expense = expenseList.get(position);
holder.title.setText(expense.getTitle());
holder.amount.setText(expense.getAmount());
mRemoveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Remove the item on remove/button click
int pos = expenseList.indexOf(expense);
if (pos == -1)
return;
expenseList.remove(pos);
notifyItemRemoved(pos);
notifyItemRangeChanged(pos, expenseList.size());
}
});
}