【发布时间】:2021-05-01 06:26:52
【问题描述】:
我正在尝试从列表中删除项目,但出现以下错误
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline fun <T> MutableCollection<out TypeVariable(T)>.remove(element: TypeVariable(T)): Boolean defined in kotlin.collections
public inline fun <T> MutableList<TypeVariable(T)>.remove(index: Int): TypeVariable(T) defined in kotlin.collections
public inline fun <K, V> MutableMap<out TypeVariable(K), TypeVariable(V)>.remove(key: TypeVariable(K)): TypeVariable(V)? defined in kotlin.collections
Code
class EducationsAdapter(val context: Context?, private var educationList: MyEducations) : RecyclerView.Adapter<EducationsAdapter.EducationsAdapterViewHolder>() {
override fun getItemCount()= educationList.data.size
// other functions...
override fun onBindViewHolder(holder: EducationsAdapter.EducationsAdapterViewHolder, position: Int)
{
holder.educationDelete.setOnClickListener {
deleteMyEducations(currentItem.id, position)
}
}
//delete
private fun deleteMyEducations(id: String, position: Int) {
// ".remove" is returning error above
educationList.remove(position)
notifyDataSetChanged()
}
}
有什么建议吗?
更新
我的MyEducations 类(渲染来自服务器的数据)
data class MyEducations(
val data: List<Education>,
val message: String
) { }
data class Education(
val id: String,
val start: String,
val end: String,
val title: String,
val body: String,
val user: User,
val created_at: String,
val updated_at: String,
) {}
更新 2
我做了以下更改
// add
val list = mutableListOf<MyEducations>()
private fun deleteMyEducations(id: String, position: Int) {
//changed to
list.remove(educationList.data[position])
notifyDataSetChanged()
}
它的作用是闪烁删除项目(意思:不到一秒钟我的项目删除并再次返回列表)!
【问题讨论】:
-
MyEducations 的类型是什么?它是可变的吗?如果不将其创建为 MutableList 并使用 remove。
-
@mangupt 更新了我的问题
-
val data: List<Education>是非可变类型。请尝试val data: MutableList<Education> -
@mangupt
Property must be initialized or be abstract你介意发布答案吗?我可能放错地方了! -
将列表类型更改为
MutableList或ArrayList。附带说明一下,您的适配器应该只对List<Education>感兴趣,而不是对MyEducations感兴趣。MyEducations这只是一个包装类,如果你不将它传递给适配器,你会更好地使用它,只需将myEducations.data传递给适配器,然后从列表中删除项目。
标签: android kotlin android-recyclerview android-adapter