我正在努力提高我的应用程序的稳定性和性能,但目前在Android Studio中卡在了一个警告上。请看下面的Adapter类:
private class CoinsAdapter(private val fragment: CoinFragment, private val coins: List<Coin>): RecyclerView.Adapter<CoinsAdapter.ViewHolder>(), Filterable {
private val filter = ArrayList(coins)
override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
val binding = ItemCoinBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val coin = filter[position]
holder.binding.coinImage.setImageResource(coin.image)
holder.binding.coinText.text = builder.toString()
}
override fun getItemCount() = filter.size
override fun getFilter() = object : Filter() {
override fun performFiltering(constraint: CharSequence): FilterResults {
if (constraint.length < 2) return fetchResults(coins)
val pattern = constraint.toString().lowercase().trim()
val filter = arrayListOf<Coin>()
for (coin in coins) if (coin.name.lowercase().contains(pattern)) filter.add(coin)
return fetchResults(filter)
}
private fun fetchResults(coins: List<Coin>): FilterResults {
val results = FilterResults()
results.values = coins
return results
}
override fun publishResults(constraint: CharSequence, results: FilterResults) {
filter.clear()
filter.addAll(results.values as List<Coin>)
notifyDataSetChanged()
}
}
private inner class ViewHolder(val binding: ItemCoinBinding) : RecyclerView.ViewHolder(binding.root)
}
适配器和过滤器运行得非常好,但是请注意
publishResults
函数。Android Studio警告与notifyDataSetChanged
相关。
如果可以,始终使用更具体的更改事件效率会更高。只有在万不得已时才依赖notifyDataSetChanged。
然而,我不知道如何在这种情况下(使用过滤器)使用notifyDataSetChanged
。什么是正确的方法,如何在这种情况下使用它?