在MainActivity
中,它有一个spinner
,该项目是使用Coroutine
从服务器获取的
代码
fun getList() {
val service = RetrofitFactory.makeRetrofitService()
GlobalScope.launch(Dispatchers.Main) {
val request = WebApi.getList(context)
request?.userName.let {
for (i in it!!.iterator()) {
list.put("", "")
list.put("None","None")
list[i.name!!] = i.id!! // Ali
}
spinnerName?.let { spn ->
spn.adapter = ArrayAdapter(context, R.layout.spinner_item, list.keys.toTypedArray())
val position = (spn.adapter as ArrayAdapter<String>).getPosition("")
spn.setSelection(position)
}
}
}
}
首先,我希望微调框默认显示empty
。当用户单击微调器时,它只会显示两个项目,分别是“无”和“阿里”。
我该如何实现?
到目前为止,我可以将空字符串设置为默认值,但是当我单击时,微调器中有3个项目,分别是None,Ali和空字符串。
答案 0 :(得分:1)
要将您的empty
设置为默认值,但不在下拉列表中,您可以做的是提供适配器列表,该适配器列表的末尾包含empty
实体,但 >适配器计数,请使用getCount()
方法减少计数。这样最后一个条目将在下拉列表中被忽略。
看看如何做到:
val list = arrayListOf("None","Ali","Empty") // You can provide any type of list here
val adapter = object : ArrayAdapter<String>(context, itemLayout, list) {
//Override getCount method and we reduce one count less when list is there, so that last entry would be ignored in dropdown.
override fun getCount(): Int {
val count = super.getCount()
return if (count > 0) count - 1 else count
}
}
your_spinner.adapter = adapter
your_spinner.setSelection(list.size-1) // We make our last list item as default entry
编辑O.P。:
spinnerName?.let { spn ->
val adapterList = list.keys.toMutableList().apply { this.add("Empty") }
spn.adapter = object : ArrayAdapter<String>(context, R.layout.spinner_item, adapterList) {
//Override getCount method and we reduce one count less when list is there, so that last entry would be ignored in dropdown.
override fun getCount(): Int {
val count = super.getCount()
return if (count > 0) count - 1 else count
}
}
spn.setSelection(adapterList.size - 1)
}