我试图在片段启动时让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)
}
尝试以下更改,它奏效了!
LinearLayoutManager manager = new LinearLayoutManager(Application.Context);
manager.setStackFromEnd(true);
mRecyclerView.SetLayoutManager(manager);