简体   繁体   中英

Kotlin / Android Custom RecyclerView issue

I was trying to make a custom RecyclerView with Adapter which takes a HashMap as parameter, I succeeded but now only 1 item is showing in recyclerView list and I have no idea why.

Here my code snippet:

Custom 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
}

}

Initialization:

// 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
    }

And finally, custom XML for row:

<?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" />

Despite everything seems to be OK, I get only 1 row showing " milk ".

Thanks for all help!

position in override fun onBindViewHolder(holder: ViewHolder, position: Int) starts at index 0. So in your case, it will be [0, 1] and your map keys are [1, 2]. Only key "1" will be displayed correctly.

try:

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

But no need to use a map here! Just use a simple list of ProductEntry .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM