Kotlin 使用 Spinner控件
原创
©著作权归作者所有:来自51CTO博客作者董国森的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.获取选中id以及选中Text
private lateinit var sp_reason_remarks: Spinner
sp_reason_remarks.selectedItemId.toInt()
sp_reason_remarks.selectedItem.toString()
2.选中退出后回显(带其他选项)
private fun setSpinText(spin: Spinner, text: String) {
for (i in 0 until spin.adapter.count) {
if (spin.adapter.getItem(i).toString() == text) {
spin.setSelection(i)
reason_remarks_other.visibility = View.GONE
break
} else if (i == spin.adapter.count - 1) {
spin.setSelection(i)
reason_remarks_other.visibility = View.VISIBLE
reason_remarks_other.setText(text)
}
}
}
3.设置监听事件
sp_reason_remarks.onItemSelectedListener = this
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
when (position) {
arr_reason_remarks.size - 1 -> {
// reason_remarks_other是编辑其他选项内容,选中非其他时隐藏
reason_remarks_other.visibility = View.VISIBLE
reason_remarks_other.setText(reasonRemarksCheck)
}
else -> {
reason_remarks_other.visibility = View.GONE
}
}
}
4.绑定适配器
var arr_reason_remarks = resources.getStringArray(R.array.sp_reason_remarks)
val adapter = ArrayAdapter(mContext, R.layout.other_spinner_item_view, arr_reason_remarks)
sp_reason_remarks.adapter = adapter