【问题标题】:How to make RecyclerView scroll to last position in onCreate?如何让 RecyclerView 在 onCreate 中滚动到最后一个位置?
【发布时间】:2018-12-22 01:30:58
【问题描述】:

我试图让 RecyclerView 在片段启动时移动到最后一个位置,但找不到解决方案。当在数据库中插入新的“Pagina”时,下面的代码工作得很好,它移动到最后一个位置。但是,如果我关闭并重新打开它会回到顶部。那么,如何在创建片段时让平滑滚动生效呢?

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)

}

【问题讨论】:

  • 检查this 回答我认为它可能对你有帮助。

标签: android android-recyclerview viewmodel smooth-scrolling


【解决方案1】:

尝试以下更改,它成功了!

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

【讨论】:

  • 它与行的底部对齐,而不是顶部。但它有效,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
相关资源
最近更新 更多