Android Kotlin - How To Set Spinner Selected Item
Solution 1:
Well you need to post the adapter code as well but here I am giving a sample how I will do in adapter.
val adapterGender = ArrayAdapter<String>(context, layoutCode, context.resources.getStringArray(R.array.genderArray))
overridefunonBindViewHolder(holder: ViewHolder?, position: Int) {
valdata = listOfItems[holder!!.adapterPosition]
holder.etName?.setText(data.name)
holder.spGender?.adapter = adapterGender
holder.spGender?.setSelection(adapterGender.getPosition(data.gender))
}
{
val etName: AppCompatEditText? = itemView?.findViewById(R.id.etName)
val spGender: AppCompatSpinner? = itemView?.findViewById(R.id.spGender)
init {
//listener for gender selection
spGender?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
overridefunonNothingSelected(p0: AdapterView<*>?) {
}
overridefunonItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
listOfItems[adapterPosition].gender = p0?.selectedItem.toString()
Log.d("TAG", p0?.selectedItem.toString())
}
}
}
}
so basically I am setting a onItemSelectedListener
on spinner and listening for value changes and then setting it in model/pojo for persisting and assigning in onBindViewHolder
for setting back values.
Solution 2:
Bit late to the party, but for everyone who may be looking to a more compact and/or prettier solution; try querying the array you put in the adapter.
Assuming you've saved the values array separately, either in XML or in a class field, and you know the selected value but not the position, you can get the position using the indexOf
method and first {...}
query.
So, taking your example, one could achieve this like so:
funsetSpinnerSelectionByValue(value: String) {
val xmlArray: Array<String> = context.resources.getStringArray(R.array.units) // get array from resourcesval spinner = findViewById<Spinner>(R.id.spinnerUnits) // get the spinner element
spinner.setSelection(xmlArray.indexOf(
xmlArray.first { elem -> elem == value } // find first element in array equal to value
)) // get index of found element and use it as the position to set spinner to.
}
The first
query will throw a NoSuchElement
exception if no element in the array is equal to the value
parameter, but it will be ignored and the position will default to 0.
If some magic is done on the array before inserting it into the spinner, the most common of which being inserting a null selector, there is most likely still a way of getting the correct position using the above technique.
When a null selector is inserted, for example, you could simply add + 1
just after the indexOf
method and still get the correct position in the spinner.
Post a Comment for "Android Kotlin - How To Set Spinner Selected Item"