This is my note for Udemy lesson: Advanced Android Bootcamp 2024.
1. Add Recycler View
Create a new project and drag a recycler view component to activity_main.xml
, give it id name "recyclerView".
2. Create a Layout for List Item
Name it list_item.xml
, which contains a text view with id name "tvName".
3. Create a Data Class
data class Fruit( val name: String, val supplier: String )
4. Create a Recycler View Adapt
class MyRecyclerViewAdapter( private val fruitsList: List<Fruit>, private val clickHandler: (Fruit) -> Unit ): RecyclerView.Adapter<MyViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val listItem = layoutInflater.inflate(R.layout.list_item, parent, false) return MyViewHolder(listItem, clickHandler) } override fun getItemCount(): Int { return fruitsList.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bind(fruitsList[position]) } } class MyViewHolder( private val view: View, private val clickHandler: (Fruit) -> Unit ): RecyclerView.ViewHolder(view) { fun bind(fruit: Fruit) { val myTextView: TextView = view.findViewById<TextView>(R.id.tvName) myTextView.text = fruit.name view.setOnClickListener { clickHandler(fruit) } } }
5. Edit Main Activity
class MainActivity : AppCompatActivity() { private val fruitsList = listOf<Fruit>( Fruit("Mango", "Joe"), Fruit("Apple", "Frank"), Fruit("Banana", "Tom"), Fruit("Guava", "Joe"), Fruit("Lemon", "Alex"), Fruit("Pear", "Joe"), Fruit("Orange", "Alex") ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView = findViewById<RecyclerView>(R.id.recyclerView) recyclerView.setBackgroundColor(Color.YELLOW) recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = MyRecyclerViewAdapter(fruitsList) { listItemClicked(it) } } private fun listItemClicked(fruit: Fruit) { Toast.makeText(this, "Fruit is: ${fruit.name}", Toast.LENGTH_SHORT).show() } }