Я пытаюсь реализовать Разбивка на страницы в Моем проекте, но я не понимаю, как он загружает все данные из Firestore .
Я попробовал свой собственный метод для разбиения на страницы, но я не понимаю, где я не прав с нумерацией страниц.
Код:
Назначенная переменная
lateinit var adapter: BooksListAdapter
var booksArray = arrayListOf<Book>()
var totalItemCount: Int = 0
var lastVisibleItem : Int = 0
var visibleThreshold : Int = 0
var item_count = 6
private var loading : Boolean = false
Диспетчер компоновки и объявление адаптера
val mLayoutManager = LinearLayoutManager(this)
books_list.setLayoutManager(mLayoutManager)
adapter = BooksListAdapter(arrayListOf(), singlePage, multiplePage, this)
books_list.adapter = adapter
Загрузка данных в первом представлении
private fun getBooksData() {
bookCollection
.orderBy("created_at", Query.Direction.DESCENDING)
.limit(item_count.toLong()).get()
.addOnSuccessListener { booksSnapshot ->
if (!booksSnapshot.isEmpty) {
for (bookSnapShot in booksSnapshot.documents) {
val hashmap = bookSnapShot.data
hashmap?.put("id", bookSnapShot.id)
val bookData = Gson().toJson(hashmap)
val book = Gson().fromJson<Book>(bookData, Book::class.java)
booksArray.add(book)
}
shimmer_view_container_book.stopShimmerAnimation()
shimmer_view_container_book.setVisibility(View.GONE)
rcv_book.setVisibility(View.VISIBLE)
adapter.booksList.addAll(booksArray)
adapter.notifyDataSetChanged()
}
}
.addOnFailureListener { exception ->
Toast.makeText(this, exception.message, Toast.LENGTH_SHORT).show()
}
}
и мой onaddScrollListener:
books_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView,
dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
visibleThreshold = books_list.getChildCount();
totalItemCount = mLayoutManager.getItemCount()
lastVisibleItem = mLayoutManager
.findLastVisibleItemPosition()
if (!loading && totalItemCount <= lastVisibleItem + visibleThreshold) {
getMoreBooks(adapter.getLastBook())
loading = true
}
}
})
Получить больше книг:
private fun getMoreBooks(lastBook: Timestamp) {
bookCollection
.orderBy("created_at", Query.Direction.DESCENDING)
.startAfter(lastBook)
.limit(item_count.toLong()).get()
.addOnSuccessListener {booksSnapshot ->
if (!booksSnapshot.isEmpty) {
for (bookSnapShot in booksSnapshot.documents) {
val hashmap = bookSnapShot.data
hashmap?.put("id", bookSnapShot.id)
val bookData = Gson().toJson(hashmap)
val book = Gson().fromJson<Book>(bookData, Book::class.java)
adapter.addDatainList(book)
}
}
}
}
Адаптер:
class BooksListAdapter (var booksList: ArrayList<Book>, val singlePage: View.OnClickListener, val multiplePage: View.OnClickListener, val context : Context): RecyclerView.Adapter<BooksListAdapter.ViewHolder>() {
var bookid = ""
val storageReference = FirebaseStorage.getInstance()
fun getLastBook(): Timestamp{
return booksList.get(booksList.size-1).created_at
}
fun addDatainList(book : Book){
booksList.add(book)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.single_book, parent, false)
return ViewHolder(itemView)
}
override fun getItemCount(): Int {
return booksList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (booksList.get(position).picture != "null"){
GlideApp.with(context).load(booksList[position].picture?.let { storageReference.reference.child(it) }).centerCrop().override(300, 300).into(holder.bookImage!!)
}else{
GlideApp.with(context).load(R.drawable.picture).centerCrop().override(300, 300).into(holder.bookImage!!)
}
holder.bookCard!!.setOnClickListener {
if (booksList[position].pages > 1){
bookid = booksList.get(position).id
multiplePage.onClick(it)
}else{
bookid = booksList.get(position).id
singlePage.onClick(it)
}
}
holder.bookTitle!!.setText(booksList[position].book_name)
holder.bookPages!!.setText("Book Pages : ${booksList[position].pages}")
holder.bookAuther!!.setText(booksList[position].auther)
holder.bookDescription!!.setText(booksList[position].book_description)
}
class ViewHolder (itemView: View) : RecyclerView.ViewHolder(itemView) {
var bookCard: CardView? = null
var bookTitle: TextView? = null
var bookDescription: TextView? = null
var bookPages: TextView? = null
var bookAuther: TextView? = null
var bookImage : ImageView? = null
init {
this.bookCard = itemView.findViewById(R.id.single_book_card)
this.bookTitle = itemView.findViewById(R.id.book_title_txt)
this.bookDescription = itemView.findViewById(R.id.book_desc_txt)
this.bookAuther = itemView.findViewById(R.id.auther_txt)
this.bookPages = itemView.findViewById(R.id.book_pages)
this.bookImage = itemView.findViewById(R.id.book_img)
}
}
}
Заранее спасибо
Если вы хотите заболеть, предоставьте другую информацию