Search code examples
androidandroid-recyclerviewviewmodelsmooth-scrolling

How to make RecyclerView scroll to last position in onCreate?


I was trying to just make the RecyclerView move to last position when the fragment is started, but cant find a solution. The code below works just fine when a new "Pagina" in inserted in database, it moves to last position. But, if I close and reopen it goes back to the top. So, how to make the smoothscroll work when the fragment is created?

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    appDatabase = AppDatabase.getDatabase(requireContext())

    val smoothScroller = object : LinearSmoothScroller(context) {
        override fun getVerticalSnapPreference(): Int = SNAP_TO_START
    }
    viewModelo = ViewModelProviders.of(this).get(ViewModelo::class.java)
    // Create the observer which updates the UI.
    val listPaginas = Observer <List<Pagina>> {
        // Update the UI, in this case, a TextView.

        recyclerViewAdapter?.addItens(it)  
            if (it.size < 1) {               
            smoothScroller.targetPosition = it.size
            } else {
               smoothScroller.targetPosition = it.size-1
        }      

        recyclerView?.layoutManager?.startSmoothScroll(smoothScroller)
    }

    viewModelo?.todasPaginas()?.observe(this, listPaginas)

}

Solution

  • Try below changes, it worked!

    LinearLayoutManager manager = new LinearLayoutManager(Application.Context);
    manager.setStackFromEnd(true); 
    mRecyclerView.SetLayoutManager(manager);