In a customized RecyclerView.Adapter<CustomAdapter.ViewHolder>
, I set an adapter for a spinner and found that the value of my spinner isn't change after selection, so I tried to add an OnItemClickListener
on my spinner:
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
// The selectable items of the spinner is dynamically generated from getItems() function
val selectableItems: List<String> = getItems()
val spinnerAdapter = ArrayAdapter<String>(this.context, androi.R.layout.simple_spinner_item)
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerAdapter.addAll(selectableItems)
viewHolder.mySpinner.adapter = spinnerAdapter
// the error occurs on the following line:
viewHolder.mySpinner.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
adapterView.setSelection(i)
}
viewHolder.mySpinner.setSelection(origionSelectedPosition)
}
I didn't get any warning or error while compiling, however during run time, I got a RuntimeException said that setOnItemClickListener cannot be used with a spinner
. It is kind of strange. Did I do anything wrong in my code? Or does anyone know why my spinner didn't change with the corresponding selection?
Further description for Kotlin solution:
I had ever tried to use onItemSelectedListener
but failed to find a suitable way to use it in kotlin.
But finally! The following code solved my problem:
viewHolder.mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {
}
override fun onNothingSelected(parent: AdapterView<out Adapter>?) {
}
}
spinner.onItemSelectedListener
– Batman