代码在Java中运行,但在转换为Kotlin时,它已不再适用。它会抛出IndexOutOfBoundsException
。
这是最初的Java:
grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItem = ((TextView) view.findViewById(R.id.tag_name)).getText().toString();
for (int j = 0; j < itemList.size(); j++){
String tempString = itemList.get(j);
if(tempString.equals(selectedItem)) {
Log.d("Update", "Removing: " + selectedItem);
itemList.remove(j);
}
}
}
});
这是新的Kotlin:
grid_view!!.onItemClickListener = AdapterView.OnItemClickListener { _, _, _, _ ->
val selectedItem = (tag_name as TextView).text.toString()
itemList.indices.forEach {
val tempString = itemList[it]
if (tempString == selectedItem) {
Log.d("Update", "Removing: " + selectedItem)
itemList.removeAt(it)
}
}
}
答案 0 :(得分:3)
由于indices
是第一次初始化,因此从indices
删除元素后,forEach
操作的List
永远不会更改,但{{1}在Java中更改,例如:
size()
对于Kotlin中的可变操作,请改为使用 MutableCollection#removeIf / MutableCollection#removeAll,例如:
// v--- `size` is changed after remove item from List
for (int j = 0; j < itemList.size(); j++){
//...
}
AND 您的Java代码逻辑错误,例如:
itemList.removeIf { it == selectedItem } // java-8
itemList.removeAll { it == selectedItem } // Kotlin