Ad

How Can I Bind RecyclerView Item That Represents Class Object With This Class Object? Kotlin

I have RecyclerView in my activity with items LiveData<List<Class>>. I need to get class object which represents with RecyclerView item that was clicked.

Now I setting id of class object inside invisible TextView field. I know that this is bad way to resolve this problem. Here is my RecyclerAdapter code

override fun onBindViewHolder(holder: AlarmsRecyclerAdapter.AlarmItemHolder, position: Int) {
        mAlarmViewModel = ViewModelProviders.of(fragment)[AlarmViewModel::class.java]
        if (mAlarms != null) {
            val current = mAlarms!!.get(position)

            // Here i set the id. I know that this is wrong way
            holder.view.alarm_id.text = current.id.toString()

            holder.view.edit_time_button.text = current.printTime()
            holder.view.switch_alarm_enabled.isChecked = current.enabled

            holder.view.switch_alarm_enabled.setOnClickListener {
                current.enabled = !current.enabled
                mAlarmViewModel.insert(current)
                notifyDataSetChanged()
            }
        } else {
            // Covers the case of data not being ready yet.
            holder.view.edit_time_button.text = "no timer"
        }
    }

And here is my RecyclerView item

class AlarmItemHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
        var view: View = v

        init {
            v.setOnClickListener(this)
        }

        override fun onClick(v: View) {
            Log.d("RecyclerView", "CLICK!")

            var intent = Intent(v.context, AlarmActivity::class.java)
            intent.putExtra("alarm_id", view.alarm_id.text.toString().toInt())
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            v.context.startActivity(intent)
        }

So how can I bind class item with RecyclerView item?

Ad

Answer

Add parameter to your view holder constructor . Like that

AlarmItemHolder(v: View, data : Data)
Ad
source: stackoverflow.com
Ad