Firestore 文档提供了有关使用 RecyclerView 实现滚动场景分页的有限指导。尽管遵循官方文档,用户可能会遇到困难。
要对 Firestore 中的数据进行分页并逐步在 RecyclerView 中显示,请按照以下步骤操作:
// ... // Define the query limit private val limit = 15 // Initial query val query = productsRef.orderBy("productName", Query.Direction.ASCENDING).limit(limit) query.get().addOnCompleteListener { task -> if (task.isSuccessful) { for (document in task.result!!) { val productModel = document.toObject(ProductModel::class.java) list.add(productModel) } productAdapter.notifyDataSetChanged() lastVisible = task.result!!.documents[task.result!!.size() - 1] // RecyclerView scroll listener recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { isScrolling = true } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val linearLayoutManager = recyclerView.layoutManager as LinearLayoutManager val firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition() val visibleItemCount = linearLayoutManager.childCount val totalItemCount = linearLayoutManager.itemCount if (isScrolling && (firstVisibleItemPosition + visibleItemCount == totalItemCount) && !isLastItemReached) { isScrolling = false val nextQuery = productsRef.orderBy("productName", Query.Direction.ASCENDING).startAfter(lastVisible).limit(limit) nextQuery.get().addOnCompleteListener { t -> if (t.isSuccessful) { for (d in t.result!!) { val productModel = d.toObject(ProductModel::class.java) list.add(productModel) } productAdapter.notifyDataSetChanged() lastVisible = t.result!!.documents[t.result!!.size() - 1] if (t.result!!.size() < limit) { isLastItemReached = true } } } } } }) } } // ...
提供的解决方案有效地处理滚动场景中RecyclerView 的分页。它确保用户滚动时及时检索数据,提供无缝的加载体验。
以上是如何为Android RecyclerView滚动高效地分页Firestore数据?的详细内容。更多信息请关注PHP中文网其他相关文章!