我知道有几个问题涉及如何在第一次选择之前为 Spinner
添加“Select one...”提示。但这不是我的情况。
我需要的是在 SpinnerAdapter
为空时仅显示提示。默认情况下,在这种情况下,点击时不会发生任何事情(但这不是主要问题),最重要的是,微调器不显示任何文本,所以它看起来像这样,这显然感觉不对:
知道如何简单地处理这个问题吗?我提出了 2 种可能的解决方案,但我不太喜欢其中任何一种:
- 如果
SpinnerAdapter
为空,则从布局中隐藏Spinner
并显示一个与 Spinner 具有相同背景的TextView
。 - 实现自定义
SpinnerAdapter
,如果内部列表为空,其getCount()
返回1
而不是0
,同时,让它的getView()
返回一个TextView
,其中包含所需的“空”消息,可能是灰色的。但这需要具体检查所选项目是否不是“空”项目。
最佳答案
您可以使用下面的 SpinnerWithHintAdapter
类
class SpinnerWithHintAdapter(context: Context, resource: Int = android.R.layout.simple_spinner_dropdown_item) :
ArrayAdapter<Any>(context, resource) {
override fun isEnabled(position: Int): Boolean {
return position != 0
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return (super.getDropDownView(position, convertView, parent) as TextView).apply {
if (position == 0) {
// Set the hint text color gray
setTextColor(Color.GRAY)
} else {
setTextColor(Color.BLACK)
}
}
}
fun attachTo(spinner: Spinner, itemSelectedCallback: ((Any?) -> Unit)? = null) {
spinner.apply {
adapter = this@SpinnerWithHintAdapter
itemSelectedCallback?.let {
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
val selectedItem = parent?.getItemAtPosition(position)
// If user change the default selection
// First item is disable and it is used for hint
if (position > 0) {
it(selectedItem)
}
}
}
}
}
}
}
如何使用?假设我有一个名为 City
data class City(
val id: Int,
val cityName: String,
val provinceId: Int
) {
/**
* By overriding toString function, you will show the dropdown text correctly
*/
override fun toString(): String {
return cityName
}
}
在 Activity 中,启动适配器,添加提示(第一项),添加主要项目,最后将其附加到您的微调器。
SpinnerWithHintAdapter(this@MyActivity)
.apply {
// add hint
add("City")
// add your main items
for (city in cityList) add(city)
// attach this adapter to your spinner
attachTo(yourSpinner) { selectedItem -> // optional item selected listener
selectedItem?.apply {
if (selectedItem is City) {
// do what you want with the selected item
}
}
}
}
关于android - Spinner - 适配器为空时显示提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18646726/