package com.example.bookapp
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class BookAdapter(
// The constructor lets the Activity tell the adapter
// what should happen when a book is clicked.
// Here you are passing into the constructor a Function - A BEHAVIOR
// It returns a Behavior, not a value
// onItemClick — saves the function so the adapter can use it inside the ViewHolder.
// When the user clicks a row, open the EditBookActivity
// and tell it which row was clicked
private val onItemClick: (Int) -> Unit
) : RecyclerView.Adapter<BookAdapter.BookViewHolder>() {
inner class BookViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val title: TextView = view.findViewById(R.id.textTitle)
val author: TextView = view.findViewById(R.id.textAuthor)
init {
view.setOnClickListener {
onItemClick(bindingAdapterPosition)
}
// This means: “When someone taps this row, call the function the Activity gave me,
// and tell it my position.”
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_book, parent, false)
return BookViewHolder(view)
}
override fun onBindViewHolder(holder: BookViewHolder, position: Int) {
val book = BookRepository.books[position]
holder.title.text = book.title
holder.author.text = book.author
}
override fun getItemCount(): Int = BookRepository.books.size
}