我如何访问回收站视图内的按钮?

问题描述 投票:0回答:1

这是我的RecyclerView Adaper

class RecyclerAdapter(priv val recyclerList:List):RecyclerView.Adapter(){

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): mainRecyclerViewHolder {
    val itemView = LayoutInflater.from(parent.context).inflate(R.layout.quiz_item_recycler_view,
        parent, false)

    return mainRecyclerViewHolder(itemView)
}

override fun getItemCount() = recyclerList.size

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

    val currentItem = recyclerList[position]
    holder.imageView.setImageResource(currentItem.imageResource)
    holder.textView.text = currentItem.recyclerCardText


}

class mainRecyclerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){

    val imageView: ImageView = itemView.rec_image
    val textView: TextView = itemView.text_view_1




}

}

这是我的数据类

数据类RecyclerItemMain(val imageResource:Int,val recyclerCardText:String,val button:Button)

android kotlin button android-recyclerview onclicklistener
1个回答
0
投票

喜欢这个:

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

        holder.yourButton.setOnClickListener { v ->

            // Here your start your other activity or navigate to another fragment
        }
    }

[请记住,如果您打算根据按钮将用户发送到不同的活动,则必须创建when表达式,该表达式将根据recyclerItem中的另一个值将用户发送到活动,例如,项目,以您的情况为准currentItem.recyclerCardText

这是您的完整适配器,已重新组织:

class RecyclerAdapter(recyclerList: List<CategorySectionIcon>) :
    RecyclerView.Adapter<YourAdapter.CustomViewHolder>() {

    private var recyclerList: List<CategorySectionIcon>? = recyclerList


    inner class CustomViewHolder(
        //Get a reference to the Views in our layout//

        val myView: View
    ) : RecyclerView.ViewHolder(myView) {

        var textView: TextView = myView.findViewById(R.id.your_text)
        var imageView: ImageView = myView.findViewById(R.id.your_image)
        var yourButton: Button = myView.findViewById(R.id.iv_category_imagen_icon)

    }

    override//Construct a RecyclerView.ViewHolder//
    fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val itemView =
            layoutInflater.inflate(R.layout.quiz_item_recycler_view, parent, false)
        return CustomViewHolder(itemView)
    }

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

        holder.textView.text = recyclerList!![position].recyclerCardText
        holder.imageView.setImageResource(recyclerList!![position].image)

        holder.yourButton.setOnClickListener { v ->

            // Here your start your other activity or navigate to another fragment
        }
    }

    //Calculate the item count for the RecylerView//
    override fun getItemCount(): Int {
        return recyclerList!!.size
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.