Kotlin Android Extensions in Adapter

Kotlin Android Extensions in Adapter

Sometimes is difficult to use kotlin android extensions, the best way to use Kotlin synthetic in Adapter or ViewHolder is like this:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = tasks[position]
holder.bind(item, checkTask, deleteTask)
}

No need to write

val tvTask = view.findViewById(R.id.tvTask)
tvTask.text = task.description

Just

 
itemView.task_item_textView.text = task.description

Or in fun bind you can put

 = with(itemView)

All the fun

fun bind(task: Task, checkTask: (Task) -> Unit, deleteTask: 
(Task) -> Unit) = with(itemView){
            task_item_textView.text = task.description
            task_item_done_checkBox.isChecked = task.completed
            task_item_done_checkBox.setOnClickListener{checkTask(task)}
            setOnClickListener { deleteTask(task) }
        }

Example in Git Hub

Leave a Reply

Your email address will not be published. Required fields are marked *