Skip to main content

How to add icons or images to items in a Spinner in Kotlin Android

How to add icons or images to items in a Spinner in Kotlin Android.

Here's a step-by-step tutorial on how to add icons or images to items in a Spinner in Kotlin Android.

Step 1: Create a new Android project in Kotlin.

Create a new Android project in Kotlin using Android Studio.

Step 2: Add dependencies.

In your project's build.gradle file, add the following dependencies:

dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
}

Step 3: Create a layout file for the Spinner item. Create a new layout file called spinner_item.xml in the res/layout directory. This layout file will define the appearance of each item in the Spinner. Here's an example of spinner_item.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<ImageView
android:id="@+id/icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@drawable/ic_android" />

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginLeft="8dp"
android:textColor="@android:color/black" />

</LinearLayout>

Step 4: Create an adapter for the Spinner.

Create a new Kotlin class called CustomSpinnerAdapter. This class will extend the ArrayAdapter class and override the getView method to customize the appearance of each Spinner item. Here's an example implementation of CustomSpinnerAdapter:

class CustomSpinnerAdapter(context: Context, items: List<String>, private val icons: List<Int>) :
ArrayAdapter<String>(context, R.layout.spinner_item, items) {

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = super.getView(position, convertView, parent)

val icon = view.findViewById<ImageView>(R.id.icon)
icon.setImageResource(icons[position])

return view
}

override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = super.getDropDownView(position, convertView, parent)

val icon = view.findViewById<ImageView>(R.id.icon)
icon.setImageResource(icons[position])

return view
}
}

Step 5: Set the adapter for the Spinner.

In your activity or fragment, create an instance of CustomSpinnerAdapter and set it as the adapter for your Spinner. Here's an example implementation:

val spinner = findViewById<Spinner>(R.id.spinner)

val items = listOf("Item 1", "Item 2", "Item 3")
val icons = listOf(R.drawable.ic_android, R.drawable.ic_apple, R.drawable.ic_windows)

val adapter = CustomSpinnerAdapter(this, items, icons)
spinner.adapter = adapter

That's it! You have successfully added icons or images to items in a Spinner in Kotlin Android.