【问题标题】:Recyclerview lose position on screen rotationRecyclerview 在屏幕旋转时失去位置
【发布时间】:2019-10-15 15:00:31
【问题描述】:

即使我使用 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 上的 recyclerview 位置状态吗?

【问题讨论】:

    标签: android kotlin android-recyclerview navigation rotation


    【解决方案1】:

    Take a look at this stackoverflow link

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这对我想要实现的目标没有帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多