问题
我已经使用外部库为回收者视图实现了多选行为。现在,为了从回收者视图中删除项目,我实现了两个for循环。第一个for循环从SQLite中删除项目,第二个for循环从适配器中删除相应的视图。但是,从适配器删除视图时会出现问题。
for (i in selectedCardItems!!.indices) //selectedCardItems stores selected card position.
{
val index = selectedCardItems!![i]
val noteRowID = listItems!![index] //list items contains references to items in SQLite and is fed to recyclerview.setadapter = myAdapter(context,listitems)
dbHandler!!.deleteNote(noteRowID.noteID!!)
}
for(i in selectedCardItems!!.indices)
{
val index = selectedCardItems!![i]
listItems!!.removeAt(i) //problem starts here, due to mismatched indexes.
adapter!!.notifyItemRemoved(i)
}
if(dbHandler!!.trashedNotesCount() == 0)
{
trashedRecyclerView!!.visibility = View.GONE
emptyTrashImg!!.visibility = View.VISIBLE
emptyTrashMsg!!.visibility = View.VISIBLE
}
selectedCardItems!!.clear() //once all operation is done,remove card positions from this ArrayList.
}
列表项和selectedCardPosition均为ArrayList类型。我知道一旦将ArrayList中的项目从索引中删除,则较高索引的项目索引会自动移至较低索引。解决此问题的有效方法是什么?
我尝试过的事情: BAD 的一项修复是基本上删除第二个for循环,该循环删除视图,然后将其替换为adapter.notifyDataSetChanged(),该循环还删除删除的动画。
答案 0 :(得分:2)
如果我正确理解了您的问题,则会出现问题,因为从列表中删除会破坏初始索引。如果是这种情况,则必须先从较高索引处开始删除,然后向下进行。因此,对循环之前降序的列表进行排序:
private static Scanner sc;
private static String firstIp;
private static String secondIp;
private static long first;
private static long second;
private static final long lastIP = 255255255255L;
private static String convertHexToIp(long hex){
String result = "";
result += (hex>>24 & 0xFF) + ".";
result += (hex>>16 & 0xFF) + ".";
result += (hex>>8 & 0xFF) + ".";
result += (hex & 0xFF);
return result;
}
private static void ipSort() {
sc = new Scanner(System.in);
System.out.println("Firtst IP");
firstIp = sc.nextLine().replaceAll("\\.", "");
first = Long.parseLong(firstIp);
if (first > lastIP || first < 1111) throw new RuntimeException("incorrect IP");
System.out.println("Second IP");
secondIp = sc.nextLine().replaceAll("\\.", "");
second = Integer.parseInt(secondIp);
if (second > 255255255 || second < 1111) throw new RuntimeException("incorrect IP");
for (long i = second; i <lastIP ; i++) {
System.out.println(convertHexToIp(second++));
}
}
public static void main(String[] args) {
ipSort();
}
}