Search code examples
androidkotlinandroid-spinner

Kotlin Spinner sselectedItem showing object not text


I've created an Adapter for my spinner and the getDropDownView is correctly displaying the custom object as it should. But after the item is selected, instead of showing that string, it shows the full object. Any help would be appreciated.

So instead of displaying:

"(${item?.code}) ${item?.name}"
eg. (Testing) Test

it just displays

Depot(id=4, name=Test, code=Testing, status_label=Error)

Spinner XML

<com.google.android.material.textfield.TextInputLayout
            android:id="@+id/depot_drop_down_container"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="15dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/userDisplayName"
            android:hint="Select Your Depot"
            android:orientation="horizontal"
            >

            <AutoCompleteTextView
                android:id="@+id/depot_drop_down"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="none"/>

</com.google.android.material.textfield.TextInputLayout>

SpinnerAdapter

class DepotSpinnerAdapter(
    context: Context, textViewResourceId: Int,
    values: List<Depot?>?
) :
    ArrayAdapter<Depot?>(context, textViewResourceId, values!!) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val label = super.getView(position, convertView, parent!!) as TextView
        label.setTextColor(Color.BLACK)
        val item = getItem(position)
        label.text = "(${item?.code}) ${item?.name}"
        return label
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val label = super.getView(position, convertView, parent!!) as TextView
        label.setTextColor(Color.BLACK)
        val item = getItem(position)
        label.text = "(${item?.code}) ${item?.name}"
        return label
    }
}

Solution

  • This turned out to be a pretty simple solution. My Depot data class needed to have the toString method overriden.

    override fun toString(): String {
        return "($code) $name"
    }
    

    Complete it looks like this:

    data class Depot (
        val id: Long,
        val name: String,
        val code: String,
        val status_label: String
    ) {
        override fun toString(): String {
            return "($code) $name"
        }
    }
    

    Answer found here: Use object array list as spinner adapter