grid layout recyclerview kotlin

// Step 1: Define the RecyclerViewAdapter
class GridRecyclerViewAdapter(private val dataList: List<String>) :
    RecyclerView.Adapter<GridRecyclerViewAdapter.ViewHolder>() {

    // Step 2: Define the ViewHolder
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // Step 3: Initialize views within the ViewHolder
        val itemText: TextView = itemView.findViewById(R.id.item_text)
    }

    // Step 4: Create the ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.grid_item_layout, parent, false)
        return ViewHolder(view)
    }

    // Step 5: Bind data to the views
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.itemText.text = dataList[position]
    }

    // Step 6: Get the item count in the data list
    override fun getItemCount(): Int {
        return dataList.size
    }
}

// Step 7: Set up the RecyclerView in your activity or fragment
class YourFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_layout, container, false)

        // Step 8: Find the RecyclerView from the layout
        val recyclerView: RecyclerView = view.findViewById(R.id.gridRecyclerView)

        // Step 9: Set layout manager for the RecyclerView
        recyclerView.layoutManager = GridLayoutManager(context, 2) // Change the span count as needed

        // Step 10: Create adapter instance and attach it to the RecyclerView
        val dataList = listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5") // Replace with your data
        val adapter = GridRecyclerViewAdapter(dataList)
        recyclerView.adapter = adapter

        return view
    }
}

Explanation for each step:

  1. Create a RecyclerView Adapter that will handle the data for the RecyclerView.
  2. Define a ViewHolder to manage the individual items' views within the RecyclerView.
  3. Initialize the views inside the ViewHolder.
  4. Create the ViewHolder when needed by inflating the item layout.
  5. Bind the data to the views within the ViewHolder.
  6. Determine the item count based on the data list size.
  7. Set up a Fragment (or an Activity) to contain the RecyclerView.
  8. Find the RecyclerView from the layout.
  9. Set the layout manager for the RecyclerView (here, a GridLayoutManager with a span count of 2).
  10. Create an instance of the adapter and attach it to the RecyclerView, providing it with the data to display.