Open In App

Step-by-Step Guide to Creating a Custom Spinner in Kotlin for Android

Last Updated : 01 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Android development, a Spinner allows users to select an item from a dropdown menu. While the default ArrayAdapter provides basic functionality, customizing a Spinner can enhance its appearance and usability. This article will guide you through creating a custom Spinner using Kotlin. You'll learn how to design a unique item layout, implement a custom adapter, and integrate it into your activity. By following these steps, you'll be able to replace the standard ArrayAdapter with your custom adapter to display both images and text in your Spinner items.

spinner_output
Custom spinner to select any item


1. Create a Layout for Spinner Items

We need a layout file that defines how each item in the spinner will look. This layout includes an ImageView and a TextView.

Step-by-Step:

  • Navigate to your res/layout directory.
  • Create a new XML file named item_spinner.xml.
  • Add the following XML code to define the layout for spinner items:
item_spinner.xml
  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:padding="8dp">

      <ImageView
          android:id="@+id/spinner_icon"
          android:layout_width="40dp"
          android:layout_height="40dp"
          android:src="@drawable/ic_launcher_background" />

      <TextView
          android:id="@+id/spinner_text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginStart="8dp"
          android:textSize="20sp"
          android:textColor="@android:color/black" />
  </LinearLayout>


2. Create a Model Class

Define a Kotlin data class to represent each item in the spinner. This class will hold the data such as the icon resource ID and the algorithm name.

Step-by-Step:

  • Create a new Kotlin file named Item.kt.
  • Add the following code to define the model class:

File: Item.kt

Item.kt
package com.gfg.custom_spinner_kotlin

// Model class to represent each item in the spinner
data class Item(val iconResId: Int, val itemName: String)


3. Create a Custom Adapter

Implement a custom adapter that binds data to the spinner using the custom layout. This adapter will map each item to its corresponding view.

Step-by-Step:

  • Create a new Kotlin file named ItemAdapter.kt.
  • Add the following code to define the custom adapter:
ItemAdapter.kt
package com.gfg.custom_spinner_kotlin

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

// Custom adapter for the spinner
class ItemAdapter(private val context: Context, private val items: List<Item>) : BaseAdapter() {

    override fun getCount(): Int = items.size

    override fun getItem(position: Int): Any = items[position]

    override fun getItemId(position: Int): Long = position.toLong()

    // Create and return the view for each item in the spinner
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val inflater = LayoutInflater.from(context)
        val view = inflater.inflate(R.layout.item_spinner, parent, false)

        val item = getItem(position) as Item

        // Bind data to views
        val icon = view.findViewById<ImageView>(R.id.spinner_icon)
        val text = view.findViewById<TextView>(R.id.spinner_text)

        icon.setImageResource(item.iconResId)
        text.text = item.itemName

        return view
    }
}


4. Update Your Layout File

Add a Spinner to your activity layout file where you want the spinner to appear.

Step-by-Step:

  • Open your activity layout XML file (e.g., activity_main.xml).
  • Add the following XML code to include the spinner:

File: res/layout/activity_main.xml

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:textStyle="bold"
        android:text="Custom Spinner"
        android:textAlignment="center"
        android:textSize="18sp"
        android:background="#4CAF50"
        android:textColor="@color/white"
        android:layout_marginBottom="100dp"
        />
    
    <TextView
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select any Item:"
        android:textStyle="bold"
        android:textSize="20sp"
        android:paddingHorizontal="24dp"
        android:layout_marginHorizontal="16dp"
        />
    <Spinner

        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:gravity="center"
        android:padding="24dp"
        android:layout_margin="24dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</LinearLayout>


5. Initialize the Spinner in Your Activity

Set up the spinner in your activity by creating an instance of the custom adapter and attaching it to the spinner. Handle item selections to display a toast message.

Step-by-Step:

  • Open your activity Kotlin file (e.g., MainActivity.kt).
  • Add the following code to initialize the spinner and handle item selections:

File: MainActivity.kt

MainActivity.kt
package com.gfg.custom_spinner_kotlin

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val spinner: Spinner = findViewById(R.id.spinner)

        // Prepare data for the spinner
        val items = listOf(
            Item(R.drawable.pizza, "Pizza"),
            Item(R.drawable.burger, "Burger"),
            Item(R.drawable.salad, "Salad"),
            Item(R.drawable.ice_cream, "Ice cream"),
            Item(R.drawable.cold_drink, "Cold Drink"),
            Item(R.drawable.pasta, "Pasta")
        )

        // Create and set the custom adapter for the spinner
        val adapter = ItemAdapter(this, items)
        spinner.adapter = adapter

        // Handle item selection
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val selectedItem = items[position]
                // Show a toast message with the selected item's name
                Toast.makeText(this@MainActivity, "Selected: ${selectedItem.itemName}", Toast.LENGTH_SHORT).show()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // Handle case when nothing is selected if needed
            }
        }
    }
}

Output:

demo_image
Output the above code


Git Link for the Application : Click Here to check whole Application


Next Article

Similar Reads