Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a click listener to my recycler view (Android kotlin) [duplicate]

I have a recycler view with 2 elements.I want to add 2 buttons in order to do different things(depends on which element of the recycler view.How is it possible to do that?My elements are 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

    }
}
like image 552
Alex Kolydas Avatar asked Aug 21 '18 08:08

Alex Kolydas


1 Answers

Try this

 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()
        }


    }
like image 70
AskNilesh Avatar answered Nov 10 '22 18:11

AskNilesh