Michael
Michael

Reputation: 111

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?

Upvotes: 1

Views: 74

Answers (1)

G&#246;kberk Yağcı
G&#246;kberk Yağcı

Reputation: 436

Add parameter to your view holder constructor . Like that

AlarmItemHolder(v: View, data : Data)

Upvotes: 2

Related Questions