【问题标题】:Kotlin / Android Custom RecyclerView issueKotlin / Android 自定义 RecyclerView 问题
【发布时间】:2018-12-25 07:47:32
【问题描述】:

我试图用适配器制作一个自定义的RecyclerView,它以HashMap 作为参数,我成功了,但现在recyclerView 列表中只显示了一项,我不知道为什么。

这是我的代码 sn-p:

自定义 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 行显示“milk”。

感谢大家的帮助!

【问题讨论】:

    标签: android android-recyclerview kotlin hashmap


    【解决方案1】:

    override fun onBindViewHolder(holder: ViewHolder, position: Int) 中的position 从索引 0 开始。 因此,在您的情况下,它将是 [0, 1],而您的地图键是 [1, 2]。只有键“1”会正确显示。

    尝试:

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

    但这里不需要使用地图!只需使用ProductEntry 的简单列表即可。

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2021-10-13
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多