How to Create a Spinner with a Custom Object

Shrayan Bajracharya
2 min readJul 14, 2020
Photo by Tim Mossholder on Unsplash

Create a Spinner and a Custom Class

First of all, we must define Spinner in our XML layout.

Now let’s create a class named CustomClass that we are going to use in our Spinner.

As we have created the class, let’s define a variable for Spinner in our Kotlin code. Since we need to display data in our Spinner using an Adapter let’s also define an ArrayAdapter variable that holds our custom objects.

Now, we should instantiate these variables in onViewCreated() if it is a fragment or onCreate() if it is an activity.

Populate Spinner with Sample Data

Also, let’s prepare a list of custom objects with sample data and add it to our adapter.

Now if we run our app we can see our sample data as follows:

The reason for our data to be displayed in this way is because the toString() of the data class is called for displaying data in the Spinner. We can simply override the toString() method and return the name field of our CustomClass so that only the name is displayed instead of the whole object data. (You can customize the toString() as per your preference on what to display in the options list of Spinner)

Now we are getting our desired result.

Implement Listener for Item Selection

Since we have finished populating our Spinner, let’s move on to determining which item is selected. For that, we can use onItemSelectedListener on our Spinner variable.

Then in the onItemSelected() function, we can get our selected object by using selectedItem (getSelectedItem()). Also, it is important to typecast the result of selectedItem to our custom class.

Final Result

Finally, our Kotlin code should look like this:

This way we can use custom objects in our Spinner.

Hope it helped you. Thank You!

--

--