如何将代表类对象的RecyclerView项与此类对象绑定?科特林

时间:2019-03-29 07:38:24

标签: android mvvm kotlin android-recyclerview

我的活动中有RecyclerView,有LiveData<List<Class>>个项目。我需要获得一个类对象,该对象代表被点击的RecyclerView个项目。

现在,我在不可见的TextView字段中设置类对象的ID。我知道这是解决此问题的不好方法。 这是我的 RecyclerAdapter 代码

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"
        }
    }

这是我的RecyclerView物品

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

那么如何将类项与RecyclerView项绑定?

1 个答案:

答案 0 :(得分:2)

向您的视图持有器构造函数添加参数。像这样

AlarmItemHolder(v: View, data : Data)