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
}