如何将点击监听器添加到我的回收器视图(Android kotlin)[重复]

Posted

技术标签:

【中文标题】如何将点击监听器添加到我的回收器视图(Android kotlin)[重复]【英文标题】:How to add a click listener to my recycler view (Android kotlin) [duplicate] 【发布时间】:2019-01-27 09:45:42 【问题描述】:

我有一个带有 2 个元素的回收站视图。我想添加 2 个按钮来做不同的事情(取决于回收站视图的哪个元素。怎么可能做到这一点?我的元素是 textviews

SettingsActiv.kt

class SettingsActiv : AppCompatActivity() 

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)

        val arrow_backBtn = findViewById(R.id.settingsToolbarBtn) as Button
        arrow_backBtn.setOnClickListener
            startActivity(Intent(this, MainActivity::class.java))
        

        val linearLayout  = findViewById(R.id.constr) as LinearLayout
        val recyclerView =  RecyclerView(this)
        val series = ArrayList<SeriesModel>()
        recyclerView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        series.add(SeriesModel("Unit of length","Meter"))
        series.add(SeriesModel("Unit of temperature","Celcius"))
        val adapter = MyAdapter(series)
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
        recyclerView.adapter = adapter
        linearLayout.addView(recyclerView,1)

MyAdapter.kt

class MyAdapter(private val seriesList: ArrayList<SeriesModel>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() 


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapter.MyViewHolder 
        val v = LayoutInflater.from(parent.context).inflate(R.layout.activity_settings_child, parent, false)
        return MyViewHolder(v)
    

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) 
        holder.textViewName.text = seriesList[position].name
        holder.textViewNameDesc.text = seriesList[position].desc

    

    override fun getItemCount(): Int 
        return seriesList.size
    

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) 
        val textViewName = itemView.findViewById(R.id.name) as TextView
        val textViewNameDesc = itemView.findViewById(R.id.desc) as TextView

    

【问题讨论】:

【参考方案1】:

试试这个

 override fun onBindViewHolder(holder: MyViewHolder, position: Int) 
        holder.textViewName.text = seriesList[position].name
        holder.textViewNameDesc.text = seriesList[position].desc

        holder.textViewName.setOnClickListener 
            Toast.makeText(context,"clicked",Toast.LENGTH_SHORT).show()
        


    

【讨论】:

非常感谢!!!(我会在5分钟内接受答复!) @AlexKolydas 很乐意为您提供帮助 我想你想在你的 recyclerview 右边有两个按钮 是的,我会按照 Nilesh 向我展示的方式去做! 哦,对对对..希望你成功.. :)

以上是关于如何将点击监听器添加到我的回收器视图(Android kotlin)[重复]的主要内容,如果未能解决你的问题,请参考以下文章

回收站视图点击动画

如何在回收站视图上添加 OnItemClick 侦听器 [重复]

如何为我在回收站视图中的卡片视图中的每个项目创建一个点击监听器

RecyclerView Item Click Listener with DataBinding

OnClick 在片段的回收器适配器中无法正常工作

如何将回收器视图添加到片段