我正在尝试使用 room 和 viewmodel 在我的 recyclerview 中实现搜索功能。
该功能在搜索时运行良好。但是,如果我清空搜索字符串,recyclerview 不会滚动到完整列表的顶部。
代码下方:
View 模型
@HiltViewModel
class MyViewModel @Inject constructor(repository: MyRepository) :
ViewModel() {
private var nameFilter = MutableLiveData<String>("")
val allPosts : LiveData<List<Post>> = Transformations.switchMap(nameFilter) { name ->
if (name.isEmpty()) {
repository.getAllPosts()
} else {
repository.getPostByName(name)
}
}
fun getPostByName(name: String) {
nameFilter.postValue(name)
}
}
fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val listAdapter = MyListAdapter()
binding.RV.apply {
adapter = listAdapter
layoutManager = GridLayoutManager(context, 2)
// Just for spacing
addItemDecoration(RecyclerViewCustomItemDecorator(8, 8))
}
binding.searchRV.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(editable: Editable?) {
viewModel.getPostByName(editable.toString())
}
})
viewModel.allPosts.observe(viewLifecycleOwner) {
listAdapter.submitList(it)
}
}
Recyclerview 适配器实现 diffUtil 逻辑。
希望大家能够帮忙!谢谢
最佳答案
在回收器 View 中,当用户位于滚动底部时,有一个属性可以在顶部滚动 mRecyclerView.smoothScrollToPosition(0);
SmoothScrollToPosition 有助于在顶部平滑滚动,您也可以使用 mRecyclerView.layoutManager?.scrollToPosition(0)
如果我们使用 ScrollView ,则使用
scrollView.fullScroll(ScrollView.FOCUS_UP);。
关于android - 搜索 Recyclerview - 当搜索为空时滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67686049/