我在实现一个过滤器的时候遇到了java.lang.IndexOutOfBoundsException。在onBindViewHolder方法中出现了错误,并且位置值大于过滤列表,所以它产生了indexOutOfBoundException。我不知道为什么即使我调用了notifyDataSetChanged(),位置值也大于过滤列表。这是我的一个过滤器适配器的代码。请给予我一些解决这个问题的方法。谢谢!!
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()
}
}
}
字符串
}
1条答案
按热度按时间m3eecexj1#
这是因为你的getCount返回item_list.size,但是你正在将位置索引到filtered_list中,filtered_list是item_list的子集。getCount应该返回过滤列表的大小,而不是原始列表。通过返回原始列表的大小,这是更大的,你使回收器列表尝试显示超出过滤列表边界的项目,并导致它抛出此错误。