我的活动中有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
项绑定?
答案 0 :(得分:2)
向您的视图持有器构造函数添加参数。像这样
AlarmItemHolder(v: View, data : Data)