Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 搜索回收视图-搜索为空时滚动至顶部_Android_Mvvm_Android Recyclerview_Viewmodel - Fatal编程技术网

Android 搜索回收视图-搜索为空时滚动至顶部

Android 搜索回收视图-搜索为空时滚动至顶部,android,mvvm,android-recyclerview,viewmodel,Android,Mvvm,Android Recyclerview,Viewmodel,我正在尝试使用room和viewmodel在我的recyclerview中实现搜索功能 该功能在搜索时工作正常。但是,如果我清空搜索字符串,则recyclerview不会滚动到完整列表的顶部 代码如下: 视图模型 @HiltViewModel 类MyViewModel@Inject构造函数(存储库:MyRepository): ViewModel(){ 私有变量nameFilter=MutableLiveData(“”) val allPosts:LiveData=Transformations

我正在尝试使用room和viewmodel在我的recyclerview中实现搜索功能

该功能在搜索时工作正常。但是,如果我清空搜索字符串,则recyclerview不会滚动到完整列表的顶部

代码如下:

视图模型

@HiltViewModel
类MyViewModel@Inject构造函数(存储库:MyRepository):
ViewModel(){
私有变量nameFilter=MutableLiveData(“”)
val allPosts:LiveData=Transformations.switchMap(nameFilter){name->
if(name.isEmpty()){
repository.getAllPosts()
}否则{
repository.getPostByName(名称)
}
}
趣味getPostByName(名称:字符串){
nameFilter.postValue(名称)
}
}
片段

覆盖已创建的视图(视图:视图,savedInstanceState:Bundle?){
super.onViewCreated(视图,savedInstanceState)
val listAdapter=MyListAdapter()
绑定{
适配器=列表适配器
layoutManager=GridLayoutManager(上下文,2)
//只是为了间隔
addItemDecoration(RecycleServiceCustomomItemDecorator(8,8))
}
binding.searchRV.addTextChangedListener(对象:TextWatcher{
重写更改前的乐趣(p0:CharSequence?,p1:Int,p2:Int,p3:Int){
}
重写已更改的文本(s:CharSequence?,start:Int,before:Int,count:Int){
}
覆盖后文本更改(可编辑:可编辑?){
viewModel.getPostByName(可编辑的.toString())
}
})
viewModel.allPosts.observe(viewLifecycleOwner){
listAdapter.submitList(it)
}
}
Recyclerview适配器实现diffUtil逻辑


希望任何人都能帮忙!谢谢

在“回收器”视图中,当用户位于滚动条的底部时,有一个属性可在顶部滚动 mRecyclerView.smoothScrollToPosition(0)

SmoothScrollToPosition帮助在顶部平滑滚动中,您还可以使用mRecyclerView.layoutManager?.scrollToPosition(0)

如果我们使用滚动视图,那么使用


scrollView.fullScroll(scrollView.FOCUS\u UP)

我尝试了你的两种方法。但是,smoothScrollToPosition(0)可以正常工作—可能需要很长时间,而且看起来很难看。scrollToPosition(0)不会滚动到最顶端