回收器视图在屏幕旋转时失去位置



即使我使用ViewModel作为数据,RecyclerView每次屏幕方向变化都会滚动到顶部。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).setSupportActionBar(binding?.toolbar)

val host: NavHostFragment = activity?.supportFragmentManager
?.findFragmentById(R.id.nav_host_fragment) as NavHostFragment?
?: return
// Set up Action Bar
val navController = host.navController
// Setup bottom navigation view
binding?.bottomNav?.setupWithNavController(navController)
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater , com.angelstudio.newsapp.R.layout.fragment_feed,container , false)
myView= binding.root
return myView
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel =ViewModelProviders.of(this,viewModelFactory).get(FeedFragmentViewModel::class.java)
bindUi()
(activity as? AppCompatActivity)?.supportActionBar?.title = getString(R.string.Naws_App)
(activity as? AppCompatActivity)?.supportActionBar?.subtitle = getString(R.string.Feed)
binding.mySwiperefresh.setOnRefreshListener {
refresh()
mySwiperefresh.setRefreshing(false)
}
}

private fun bindUi()=launch {
val topHeadline =viewModel.topHeadline.await()
val naviagte =viewModel.navigateToDetail.await()
topHeadline.observe(this@FeedFragment, Observer {
if(it == null || it.isEmpty()) return@Observer
binding.recyclerView.apply {
showShimmerAdapter()
topHeadlineAdapter = TopHeadlineAdapter(TopHeadlineListener { 
url ->  viewModel.onTopHeadlineClicked(url)
})
adapter = topHeadlineAdapter
topHeadlineAdapter.submitList(it)
hideShimmerAdapter()
}
})

这是我在片段上的代码,我找不到我做错了什么,有什么东西可以处理 ViewModel 上的回收器视图位置状态吗?

看看这个堆栈溢出链接

您需要将回收器视图的位置存储在已保存的实例状态中,并且更改配置后,您必须将回收器视图滚动到存储的位置

manifestandroid:configChanges="orientation|keyboardHidden"添加到您的活动标签中,如下所示:

<activity
android:name=".activity.MainActivity"
android:configChanges="orientation|keyboardHidden"
android:theme="@style/AppTheme.NoActionBar">
</activity>

相关内容

  • 没有找到相关文章

最新更新