android - 如何在片段内使用 RecyclerView 实现无限列表
问题描述
一旦用户滚动到底部附近,我如何将更多内容加载到我的 RecyclerView 列表中?
我已经查看了这个堆栈溢出页面,但我仍在努力尝试将 Kotlin 答案中的代码实现到我的代码中。
为了像你们这样更好的上下文 id 看看我以前的问题,这向您展示了我如何在 android studio 中创建我的片段(它是通过单击片段(列表)并选择一个空片段来完成的)。
在我的 onCreateView 里面我有这段代码
view.list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val contentHeight = view.list.height - (view.list.paddingTop + view.list.paddingBottom)
val distanceToBottom = view.list.computeVerticalScrollRange() - view.list.computeVerticalScrollOffset() - contentHeight
val metrics = DisplayMetrics()
activity!!.windowManager.getDefaultDisplay().getMetrics(metrics)
//val Measuredwidth = metrics.widthPixels
val Measuredheight = metrics.heightPixels
// everything looks like its in pixels. It is important that everything is one unit type to ensure accurate calculations
// Once this is all finished i will ask a question in stack overflow on how to ensure its one unit type
// using the screen height and timesing it by 2 to know when to load more data
if (Measuredheight * 2 > distanceToBottom) {
Toast.makeText(view.list.context, "Scrolling $distanceToBottom, this is the screen height excluding the nav bar in pixels " + Measuredheight + " more content needs to be loaded", Toast.LENGTH_SHORT).show()
// Load more function to be placed here
}
}
})
- - - - - - - - - - - 编辑 - - - - - - - - - - -
我一直在研究分页库,并且遇到了本教程,但是我仍然无法将代码放入片段中。这是教程的源代码,所以这是我在项目中使用的代码。
我认为我应该做的是在我的 onCreateView 中,我必须放置这段代码
adapter = UserAdapter()
val itemViewModel = ViewModelProviders.of(view.list.context)
.get(UserViewModel::class.java)
itemViewModel.userPagedList.observe(view.list.context, Observer {
adapter.submitList(it)
})
list.adapter = adapter
但是,我遇到了错误,并且某些代码似乎已被弃用。有人可以告诉我我需要使用的代码,以便在片段内有一个 RecyclerView,以便我可以接受他们的答案。
解决方案
您正在寻找的是一个名为Paging
它的库,它是 Android 架构组件的一部分。
这是代码实验室,请注意 Paging 3 已发布https://developer.android.com/topic/libraries/architecture/paging/v3-overview
推荐阅读
- sql - 我想在最终输出表中显示来自 dbo.orders 的总金额。如何?
- mysql - 如何对 Bash 输出进行排序并将其保存到 sql db
- objective-c - Swift 选择器方法没有被调用
- shell - CMD终端传递args数组
- css - 溢出:隐藏;不适用于网格内的图像
- arrays - 如果 C 编程中两个元素相同,如何从数组中删除两个元素?
- kiwi-tcms - 带有日期范围的 tcms api 过滤器
- kubernetes - 基于实例类型的 Kubernetes Pod CPU 资源
- ios - 确定 DeepAI sdk 版本
- python - 如何在 Windows 中获取有关 AMD GPU 的完整信息