java.lang.IndexOutOfBoundsException : Invalid index

标签 java android arraylist listadapter

我有一个数组列表,并使用 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());

        }
    });
}

最佳答案

对此有许多可能的解决方案。

这对我来说是理想的

@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();
        }
    });
}

关于java.lang.IndexOutOfBoundsException : Invalid index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41939840/

相关文章:

java - 设置 JMenu,我试图在布局框的顶部创建一个不是组合框的菜单

java - 如何通过 Gradle 7.0+ 制作具有依赖项的 Jar 文件?

android - 在纵向模式android中防止滚动

java - 检查 ArrayList 中的数组元素是否包含特定值

java - 大值的数字格式异常

java - Collectors.toSet() 和 HashSet

android - 将 HashMap<Integer, List<Integer>> 放入 savedInstanceState

Android 低功耗蓝牙 (BLE) API 尚未准备好迎接黄金时段

java - Android:向 arrayList 添加超过 1 项并将其显示为一项

android - 如何在 Activity 之间传递 ArrayList<Bitmap>