Бесконечная прокрутка RecyclerView дважды выдает случайный элементAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Гость
 Бесконечная прокрутка RecyclerView дважды выдает случайный элемент

Сообщение Гость »


I am working on getting a RecyclerView to display data from a big ArrayList of gardening tips. The RecyclerView row is full screen. When user scrolls to the end of the list, a random item should be pulled.
I have it half-working. But the problem is

Код: Выделить всё

existingTipsList.add(newRandomTip) (and the print statement below it)
is being called every other swipe, which is causing the data to duplicate twice.
Here is my progress:
Adapter

Код: Выделить всё

class GardeningTipAdapter(val dataSource:ArrayList) : RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.gardening_tips_row, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return dataSource.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {

val text = dataSource[position].gardeningTipFull
holder.label.text = text
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val label: TextView = itemView.findViewById(R.id.gardening_tips_row)
}
}
Model

Код: Выделить всё

object GardeningTipsData {

fun allGardeningTips() : ArrayList{
return arrayListOf(

TipsModel("Gardening Tip 1"),
TipsModel("Gardening Tip 2"),
TipsModel("Gardening Tip 3"),
TipsModel("Gardening Tip 4"),
TipsModel("Gardening Tip 5"),
TipsModel("Gardening Tip 6"),

)
}

fun getRandomTip(currentTips: ArrayList): ArrayList {
val allTipsList = allGardeningTips()
val randomIndex = (0 until allTipsList.size).random()
val randomTip = allTipsList[randomIndex]

currentTips.add(randomTip)

return currentTips
}

}
Scroll listener

Код: Выделить всё

private val existingTipsList = ArrayList()

// Initial setup with a single random tip
existingTipsList.add(GardeningTipsData.getRandomTip(existingTipsList).last())
binding.tipRecyclerView.adapter = GardeningTipAdapter(existingTipsList)

var loading = true
var pastVisiblesItems: Int = 0
var visibleItemCount: Int = 0
var totalItemCount: Int = 0

binding.tipRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0) { // check for scroll down
visibleItemCount = mLayoutManager.childCount
totalItemCount = mLayoutManager.itemCount
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition()

if (loading) {
if (visibleItemCount + pastVisiblesItems >= totalItemCount && !lastItemAdded) {
loading = false

// Get a new random item and append it to the list
val newRandomTip = GardeningTipsData.getRandomTip(existingTipsList).last()
existingTipsList.add(newRandomTip)
println("ADDED NEW!")

// Notify the adapter that the data has changed
binding.tipRecyclerView.adapter?.notifyItemInserted(existingTipsList.size - 1)

lastItemAdded = true
loading = true
} else {
lastItemAdded = false
}
}
}
}
})
With this setup, this is what you see when you scroll through the RecyclerView:

Код: Выделить всё

Gardening Tip 5
Gardening Tip 5
Gardening Tip 1
Gardening Tip 1
Gardening Tip 4
Gardening Tip 4
Gardening Tip 2
Gardening Tip 2
Gardening Tip 2
Gardening Tip 2
Gardening Tip 1
Gardening Tip 1
The objective is to display the data at random, like the following:

Код: Выделить всё

Gardening Tip 5
Gardening Tip 4
Gardening Tip 1
Gardening Tip 3
Gardening Tip 6
Gardening Tip 1
Gardening Tip 2
Gardening Tip 3
Gardening Tip 4
Gardening Tip 5
Gardening Tip 2
Gardening Tip 5
I believe the issue is every time a new item gets appended to the arrayList, it gets added twice, which is causing the duplication. How can I adjust this so that the data displays at random and

Код: Выделить всё

existingTipsList.add(newRandomTip)
gets called when the user hits the last item?[/b]


Источник: https://stackoverflow.com/questions/781 ... item-twice
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»