【问题标题】:indexoutofboundexception while implementing Recyclerview filter实现 Recyclerview 过滤器时出现 indexoutofboundexception
【发布时间】:2021-12-25 20:41:56
【问题描述】:

我在为 recyclerView 实现过滤器时遇到了 java.lang.IndexOutOfBoundsException。 onBindViewHolder 方法出错,位置值大于过滤后的列表,导致 indexoutofboundException。尽管我进行了 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】:

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

【讨论】:

  • 非常感谢!!你完美解决了我的问题!谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 2017-04-02
  • 2012-03-25
  • 1970-01-01
  • 2019-06-19
  • 2014-05-06
相关资源
最近更新 更多