私はいくつかの拡張機能を作りました Spinner
データの読み込みと項目選択の追跡のために、作成しました。
Spinner.kt
fun <T> Spinner.load(context: Context, items: List<T>, item: T? = null) {
adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, items).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
if (item != null && items.isNotEmpty()) setSelection(items.indexOf(item))
}
inline fun Spinner.onItemSelected(
crossinline itemSelected: (
parent: AdapterView<*>,
view: View,
position: Int,
id: Long
) -> Unit
) {
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
itemSelected.invoke(parent, view, position, id)
}
}
}
使用例
val list = listOf("String 1", "String 2", "String 3")
val defaultData = "String 2"
// load data to spinner
your_spinner.load(context, list, defaultData)
// load data without default selection, it points to first item
your_spinner.load(context, list)
// for watching item selection
your_spinner.onItemSelected { parent, view, position, id ->
// do on item selection
}