首页 > 解决方案 > 如何在片段内使用 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,以便我可以接受他们的答案。

标签: androidkotlin

解决方案


您正在寻找的是一个名为Paging它的库,它是 Android 架构组件的一部分。

这是代码实验室,请注意 Paging 3 已发布https://developer.android.com/topic/libraries/architecture/paging/v3-overview


推荐阅读