0

I am trying to implement scrolling to specific position for recyclerView when Activity is loaded again (e.g. when returned from different Activity). I tried use stateRestorationPolicy but this doesn't help. Second approach to store index of visible item of RecyclerView in onPause method and try to scroll in onResume method. The problem is that index variable sometimes shows correct number, sometimes show zero. Even if index show correct number then scrollToPosition doesn't work. I tried several functions like scrollToPositionWithOffset etc.

I tried this approach Save scroll position which work perfect with this example (without binding) but on my example don't work.

This MainActivity


lateinit var binding:ActivityMainBinding
private var mLayoutManager: LinearLayoutManager? = null

override fun onCreate(savedInstanceState: Bundle?) {
             super.onCreate(savedInstanceState)
             binding = ActivityPolozkaBinding.inflate(layoutInflater)
             setContentView(binding.root)
             val exampleAdapter = ExampleAdapter(idPositionItem, this)
             exampleAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
             mLayoutManager = LinearLayoutManager(this@MainActivity)
        binding.apply {
            recyclerView.apply {
                adapter = exampleAdapter
                layoutManager = mLayoutManager
            }
            polozkaViewModel.getall(dokladIntent.toString(),idExp.toString() ).observe(this@MainActivity){
                exampleAdapter.submitList(it)
                //exampleAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

            }

This is onResume and onPause methods

override fun onPause() {
        super.onPause()
        index = mLayoutManager?.findFirstVisibleItemPosition()!!
        val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
        sharedPreferences.edit().putInt("index", index).apply()  
    }

override fun onResume() {
        super.onResume()
        val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
        index = sharedPreferences.getInt("index", -1)        
        if (index != -1){
            binding.recyclerViewObjednavka.smoothScrollToPosition(index)
            //mLayoutManager?.scrollToPositionWithOffset(index ,0)
        }

jenik2205
  • 339
  • 1
  • 3
  • 14

0 Answers0