gpt4 book ai didi

android - 从RecyclerView,Kotlin,Android Studio中删除项目时出错

转载 作者:行者123 更新时间:2023-12-02 13:18:51 26 4
gpt4 key购买 nike

我正在查看回收者 View ,我希望能够删除项目。

滑动删除时,出现此错误。

java.lang.ArrayIndexOutOfBoundsException: length=5; index=-1



我想它在滑动时没有到位

如何解决?

这是我在 Activity 中使用的代码。
private fun initRecyclerView() {
messages_recycler_view.apply {
layoutManager = LinearLayoutManager(this@MessagesListVC)
val topSpacePaddingDecoration = TopSpacingItemDecoration(30)
addItemDecoration(topSpacePaddingDecoration)
messagesAdapter = MessagesRecyclerAdaptor()
adapter = messagesAdapter


val swipeHandler = object : SwipeToDeleteCallback(this@MessagesListVC) {

override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
messagesAdapter = MessagesRecyclerAdaptor()
adapter = messagesAdapter
(adapter as MessagesRecyclerAdaptor).removeAt(viewHolder.adapterPosition)
}
}
val itemTouchHelper = ItemTouchHelper(swipeHandler)
itemTouchHelper.attachToRecyclerView(messages_recycler_view)
}
}

这是回收站适配器中的删除功能。
fun removeAt(position: Int) {
println("Tony the items count is {${messagesInfo.size}")
messagesInfo.removeAt(position)
notifyItemRemoved(position)
println("Tony the new data is $messagesInfo")
println("Tony the items count is {${messagesInfo.size}")
}

最佳答案

也许我误解了您的代码,但是我注意到的一件事是您每次滑动都会创建一个新的适配器。我不确定为什么要这么做。而且我也不知道这是否与您崩溃有关。但是在onSwiped中省略前两行时,也许行不通吗?这样就变成

override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
println("Tony the int position is $position")

if (position > 0) {
(messagesAdapter.removeAt(position))
}
}

关于android - 从RecyclerView,Kotlin,Android Studio中删除项目时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60395086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com