实现Recyclerview过滤器时出现indexoutofboundException

问题描述 投票:0回答:1

我在为 recyclerView 实现过滤器时遇到 java.lang.IndexOutOfBoundsException 。 onBindViewHolder方法发生错误,位置值大于过滤后的列表,因此导致indexoutofboundException。我不知道为什么位置值大于filteredlist,即使我进行了notifyDataSetChanged() 调用。这是我的 RecyclerView 适配器代码。请给我一些解决方案来克服这个问题。谢谢!!

class MainListAdapter(
private val context: Context,
private val item_list: MutableList<items_list>) :
RecyclerView.Adapter<MainListAdapter.ViewHolder>(),
Filterable {
var filteredList: MutableList<items_list>? = item_list

inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    val Photo = view.PhotoImg
    val item_name = view.item_name

    fun bind(item: items_list, context: Context) {
        val resourceId =
            context.resources.getIdentifier(item.photo, "drawable", context.packageName)
        Photo.setImageResource(resourceId)
        item_name.text = item.item_name
    }
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val itemView = LayoutInflater.from(context).inflate(R.layout.item, parent, false)
    return ViewHolder(itemView)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val current = filteredList?.get(position)
    if (current != null) {
        holder.bind(current, context)
    }

}

override fun getItemCount(): Int = item_list!!.size

override fun getFilter(): Filter? {
    return object : Filter() {
        override fun performFiltering(constraint: CharSequence): FilterResults {
            val charString = constraint.toString()
            filteredList = if (charString.isEmpty()) {
                item_list
            } else {
                val filteringList = ArrayList<items_list>()
                if (item_list != null) {
                    for (name in item_list) {
                        if (name.item_name.toLowerCase().contains(charString.toLowerCase())) {
                            filteringList.add(name);
                        }
                    }
                }
                filteringList
            }
            val filterResults = FilterResults()
            filterResults.values = filteredList
            return filterResults
        }

        override fun publishResults(constraint: CharSequence, results: FilterResults) {
            filteredList = results.values as ArrayList<items_list>
            notifyDataSetChanged()
        }
    }
}

}

android android-studio kotlin android-recyclerview
1个回答
0
投票

这是因为您的 getCount 返回 item_list.size,但您正在将位置索引到filtered_list,它是 item_list 的子集。 getCount 应该返回过滤列表的大小,而不是原始列表。通过返回较大的原始列表的大小,您可以使回收器列表尝试显示超出过滤列表范围的项目,并导致它抛出此错误。

© www.soinside.com 2019 - 2024. All rights reserved.