【问题标题】:How can i get the position for second model in RecyclerView Adapter如何在 RecyclerView 适配器中获取第二个模型的位置
【发布时间】:2020-12-12 14:20:57
【问题描述】:

这是我的 RecyclerView 适配器代码

class RecyclerAdapterMain(

val product: ArrayList<ModelProductMain>,

val viewmodel: ViewModelRoom,

val newitem: List<ModelItemsNew>

) :

RecyclerView.Adapter<RecyclerAdapterMain.ViewHolder>() {


class ViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview) {


    val title: TextView = itemview.product_txt
    val price: TextView = itemview.price_product
    val imageproduct: ImageView = itemview.product_image
    val btn_add_product: Button = itemview.btn_add_product
    val amount_value: TextView = itemview.amount_value
    val button_remove_product: Button = itemview.button_remove_product


}

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


    val layoutview =
        LayoutInflater.from(parent.context).inflate(R.layout.product_items, parent, false)
    return ViewHolder(layoutview)

}

override fun getItemCount(): Int = product.size


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


    val products = product[position]
    holder.title.text = products.title
    holder.price.text = products.price.toString()
    Picasso.get().load(products.image).into(holder.imageproduct)


    holder.itemView.setOnClickListener {

        val bundle = Bundle()
        val myfragment = ItemDetailsfragment()
        myfragment.arguments = bundle


        val activity = it.context as AppCompatActivity
        activity.supportFragmentManager.beginTransaction()
            .replace(R.id.homepage, myfragment)
            .commit()


        bundle.putString("title", products.title)
        bundle.putString("price", products.price.toString())
        bundle.putString("image", products.image.toString())


    }

    holder.amount_value.visibility = View.GONE
    holder.button_remove_product.visibility = View.GONE
    holder.btn_add_product.setOnClickListener {

        holder.amount_value.visibility = View.VISIBLE
        holder.button_remove_product.visibility = View.VISIBLE

            holder.amount_value++    
        
    }

}

}

问题是我希望按下按钮时产品的数量会增加......为此我需要每个项目的位置,但我的产品的第一个模型(覆盖 fun getItemCount(): Int = product. size ) 获得了我的新模型所需的位置 (val newitem: List )。

我尝试了这段代码 val productpos = newitem.position 并给我错误大小为 1 并且索引也是 1 ... 我不知道如何解决它。刚才我需要一个新模型的位置。如何获得新职位?

【问题讨论】:

    标签: android android-studio kotlin android-recyclerview


    【解决方案1】:

    试试这个:

    val productpos = newitem.get(position)
    

    然后得到总大小:

    override fun getItemCount(): Int = product.size + newitem.size
    

    【讨论】:

    • 感谢兄弟的回答...但是给我这个错误 (java.lang.IndexOutOfBoundsException: Index: 1, Size: 1)
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2017-01-28
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多