RecyclerView 添加了一个 "empty" 布局项,当我单击它时,应用程序崩溃了

RecyclerView adds a "empty" layout item and when I click it the app crashes

我没有向我的 RecyclerView 添加任何数据,但它仍然显示一个空框(我在数据布局中设置样式的框)。它因此错误消息而崩溃

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

这是我的自定义适配器:

class CustomAdapterExercise(var exerciseList: ArrayList<Exercise>, val addList: ArrayList<textAdd>) : RecyclerView.Adapter<CustomAdapterExercise.ViewHolder>() {

val typeAdd = 0
val typeExercise = 1

override fun getItemViewType(position: Int): Int {
    if (position == exerciseList.size + 1) {
        return typeAdd
    }
    else{
        return typeExercise
    }

}

//this method is returning the view for each item in the list
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapterExercise.ViewHolder {

    if (viewType == typeExercise) {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.exercise_layout, parent, false)
        return ViewHolder(itemView)

    } else {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.add_layout, parent, false)
        return ViewHolder(itemView)
    }

}

//this method is binding the data on the list
override fun onBindViewHolder(holder: CustomAdapterExercise.ViewHolder, position: Int) {
    if (holder.itemViewType == typeAdd) {
        holder.bindAdd(addList[0])
    }
    else{
        if(position != exerciseList.size){
            holder.bindItems(exerciseList[position])
        }
    }
}

//this method is giving the size of the list
override fun getItemCount(): Int {
    return exerciseList.size + 2
}

//the class is hodling the list view
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun bindItems(Exercise: Exercise) { 

        var exerciseAmount = itemView.findViewById<TextView>(R.id.exerciseAmount)

        if(exerciseAmount != null){
            exerciseAmount.text = Exercise.exAmount

        }
    }

    fun bindAdd(textAdd: textAdd){
        val addText = itemView.findViewById<TextView>(R.id.addText)
        if(addText != null){
            addText.text = textAdd.textAdd
        }

    }
}
}

即使我添加了一些数据,它仍然会在那里生成一个空框,我不明白为什么。 我想知道如何才能阻止它总是产生一个空盒子?

这些是在 RecyclerView 中计算索引的问题:

在getItemCount 中它应该是+1,而不是+2,因为它只需要为添加按钮添加一个额外的项目。

如果列表长度在getItemViewType 的末尾位置,而不是列表长度+1。这是因为位置是 0 索引的。因此,例如,如果您有 5 个项目,位置 0-4 将是您的练习项目,然后位置 5(位置 == exerciseList.size)将是一个添加项目。

在 getItemViewType 中添加位置和生成的视图类型的日志有助于调试,因为它可以非常快速地显示哪些位置计算错误。