我做了一些扩展功能,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
}