At first. When you initialize your spinner add
spinner.setSelection(0, false)
And I created this adapter with selected item:
abstract class SpinnerSelectAdapter<T>(
context: Context,
private val resource: Int,
@ColorRes private val unselectedColorResource: Int,
@ColorRes private val selectedColorResource: Int,
open var objects: List<T>
) :
ArrayAdapter<T>(context, resource, objects) {
var selectedPosition = -1
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: LayoutInflater.from(parent.context)
.inflate(resource, parent, false)
if(selectedPosition != -1) {
setView(view, getItem(position)!!)
}
return view
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: LayoutInflater.from(parent.context)
.inflate(resource, parent, false)
if(selectedPosition == position){
view.setBackgroundResource(selectedColorResource)
}else {
view.setBackgroundResource(unselectedColorResource)
}
setView(view, getItem(position)!!)
return view
}
open fun setView(view: View, item: T) {
}
open fun setEmptyView(view: View){
}
override fun getItem(position: Int): T? {
return objects[position]
}
override fun getCount(): Int {
return objects.size
}
}
Then I created adapter for String Values inherited from SpinnerSelectAdapter
class SpinnerStringAdapter(
context: Context,
resource: Int,
@ColorRes unselectedColorResource: Int,
@ColorRes selectedColorResource: Int,
override var objects: List<String>
) :
SpinnerSelectAdapter<String>(
context,
resource,
unselectedColorResource,
selectedColorResource,
objects
) {
override fun setView(view: View, item: String) {
val txt = view.findViewById<TextView>(android.R.id.text1)
txt.text = item
}
}
And after in your fragment or activity
val adapter = SpinnerStringAdapter(
requireContext(),
R.layout.spinner_item,
R.color.colorBG,
R.color.colorSubBG,
types
)
spinner.adapter = typeAdapter
spinner.setSelection(0, false)
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
adapter.selectedPosition = position
adapter.notifyDataSetChanged()
}
``