Проблема с Kotlin / Android Custom RecyclerView

Я пытался создать собственный RecyclerView с адаптером, который принимает HashMap в качестве параметра, мне это удалось, но теперь в списке recyclerView отображается только 1 элемент, и я понятия не имею, почему.

Вот мой фрагмент кода:

Пользовательский RecyclerAdapter:

class ProductsRecyclerAdapter(private val dataSet: HashMap<Int, ProductEntry>) : RecyclerView.Adapter<ProductsRecyclerAdapter.ViewHolder>() {

class ViewHolder(val linearLay: LinearLayout) : RecyclerView.ViewHolder(linearLay)

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : ProductsRecyclerAdapter.ViewHolder {

    val linearLay = LayoutInflater.from(parent.context).inflate(R.layout.test_text_view, parent, false) as LinearLayout

    return ViewHolder(linearLay)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    holder.linearLay.textView.text = dataSet[position]?.pName

    holder.linearLay.textView2.text = dataSet[position]?.pExpiry

}

override fun getItemCount(): Int {

    return dataSet.size
}

}

Инициализация:

// Setup RecyclerView
    val prod1 = ProductEntry("Milk", "04/06/1996")
    val prod2 = ProductEntry("Bread", "04/01/2012")

    val testArray : HashMap<Int, ProductEntry> = hashMapOf(1 to prod1, 2 to prod2)

    viewManager = LinearLayoutManager(this)

    viewAdapter = ProductsRecyclerAdapter(testArray)

    recyclerView = findViewById<RecyclerView>(R.id.productsRecyclerView).apply {

        setHasFixedSize(true)
        layoutManager = viewManager
        adapter = viewAdapter
    }

И, наконец, собственный XML для строки:

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/linearLay"
android:layout_width = "match_parent"
android:layout_height = "wrap_content">

<TextView
    android:id = "@+id/textView"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:text = "TextView" />

<TextView
    android:id = "@+id/textView2"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_marginLeft = "40dp"
    android:layout_weight = "1"
    android:text = "TextView" />

Несмотря на то, что вроде бы все в порядке, я получаю только 1 строку с надписью «молоко».

Спасибо за помощь!

0
0
692
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

position в override fun onBindViewHolder(holder: ViewHolder, position: Int) начинается с индекса 0. Итак, в вашем случае это будет [0, 1], а ваши ключи карты - [1, 2]. Только клавиша «1» будет отображаться правильно.

пытаться:

val testArray : HashMap<Int, ProductEntry> = hashMapOf(0 to prod1, 1 to prod2)

Но здесь не нужно использовать карту! Просто используйте простой список ProductEntry.

Другие вопросы по теме