回收器视图在更新适配器后不会自动滚动到顶部



我有一个自定义适配器和过滤器,我目前正在实现它,以根据回收器视图条目上的简单子字符串搜索来过滤回收器视图。这是我的适配器NotifyChanged()函数,它更新了 RecylerView 和我的自定义filter()函数。一切都很好,除了之后的自动滚动。

private fun notifyChanged() {
val result = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return objects.size
}
override fun getNewListSize(): Int {
return temp.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return this@DiffRecyclerViewAdapter.areItemsTheSame(objects[oldItemPosition], temp[newItemPosition])
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return this@DiffRecyclerViewAdapter.areContentsTheSame(objects[oldItemPosition], temp[newItemPosition])
}
})
objects.clear()
objects.addAll(temp)
result.dispatchUpdatesTo(this)
}

fun filter(text : String){
val ob = original_objects as ArrayList<Category>
val filtered_categories = ArrayList<T>() as ArrayList<Category>

for (category in ob){
//val temp_category = category
val list_of_subcategories = ArrayList<T>() as ArrayList<Category>
for (subcategory in category.categories){
val name_of_category = subcategory.name.toLowerCase()
if (name_of_category.contains(text)){
list_of_subcategories?.add(subcategory)
}
}
if (list_of_subcategories.size > 0){
val newCategory = Category(category.id,category.name,category.description,category.videos,list_of_subcategories)
filtered_categories.add(newCategory)
}
}
temp = filtered_categories as MutableList<T>
notifyChanged()
}

在我的SearchActivity.kt中,我有以下侦听器:

searchEditText.addTextChangedListener(object : TextWatcher{
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
adapter.filter(s.toString())
recyclerView.scrollToPosition(0)
}
})

我正在查看DiffUtilnotifyDataSetChanged()的源代码,以了解过滤后滚动的工作原理。但运气并不好。整个问题是,在我搜索文本后,回收器视图被过滤得很好。但会滚动到不一致的位置。我希望它每次都滚动回顶部,但这并没有发生。即使有scrollToPosition(0)它通常会滚动到顶部,但并非总是如此。

我认为在这种情况下滚动到顶部通常是自动的。我很好奇更新和滚动的最佳实践是什么。

它需要一些时间来更新回收器视图上的数据。意思是当您尝试滚动时,在大多数情况下都不起作用。最好在滚动前使用 200 或 300 毫秒的延迟

前任:

new Handler.postDelayed(new Runnable(){
@Override
public void run(){
recyclerView.scrollToPosition(0)
}
}, 300);

最新更新