0

even though i am using viewmodel for data ,the recyclerview keeps scrolling to the top every screen orientation change.

   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()
        }
    })

here is my code on the fragment, i can't find what i am doing wrong, is there something to handle recyclerview position state on viewmodel ?

joghm
  • 569
  • 3
  • 20

2 Answers2

0

Take a look at this stackoverflow link

You need to store the position of the recycler view in the saved instance state and once the configuration is changed you must scroll the recycler view to the stored position

Anand
  • 55
  • 6
-1

Add android:configChanges="orientation|keyboardHidden" to your activity tag in manifest like so:

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

</activity>
Squti
  • 4,171
  • 3
  • 10
  • 21