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中文網其他相關文章!