所以我正在与Kotlin一起进行这个项目,我主要使用Java,因此我试图在Kotlin中找到等效项以实现相同的功能。
我从数据库中获取一个JSONArray并将其存储在名为Congregation
的可序列化数据类中,它具有以下变量id: Int, name: String, language: String
我现在有一个注册活动,其中有一个“聚集”输入,我决定将其设置为AutoCompleteTextView
,以便我可以建议与用户键入的内容匹配的可能值。我创建了一个自定义ArrayAdapter
,当显示name
的{{1}}时效果很好(下图为
但是,当我选择这些值之一时,它将显示列表中的完整值文本
例如如果我在输入中选择“利兹,克罗斯盖茨(英语)”,它将显示Congregation
我想知道如何在选中Congregation(id=1, name=Leeds, Crossgates, language=English)
的{{1}}值的情况下将其保留在框中。
当我在选择一个项目后尝试删除框的当前值时,也会收到name
自定义阵列适配器(CongregationListAdapter.kt):
Congregation
自定义视图(congregation_list_item.xml):
IndexOutOfBoundsException Index: 1 Size: 1
配置模型(Congregation.kt):
class CongregationListAdapter(context: Activity, resourceId: Int, textView: Int, private var congregations: List<Congregation>)
:ArrayAdapter<Congregation>(context, resourceId, textView, congregations) {
private var inflater: LayoutInflater = context.layoutInflater
private lateinit var view: View
@SuppressLint("SetTextI18n")
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
if (convertView == null) {
view = inflater.inflate(R.layout.congregation_list_item, parent, false)
}
val name: TextView = view.findViewById(R.id.congregation_text)
val congregation: Congregation? = getItem(position)
if (congregation != null) {
name.text = congregation.name + " (" + congregation.language + ")"
} else {
name.text = ""
return view
}
return view
}
override fun getCount(): Int {
return congregations.size
}
@SuppressLint("SetTextI18n")
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
if (convertView == null) {
view = inflater.inflate(R.layout.congregation_list_item, parent, false)
}
val congregation: Congregation? = getItem(position)
val name: TextView = view.findViewById(R.id.congregation_text)
if (congregation != null) {
name.text = congregation.name + " (" + congregation.language + ")"
} else {
name.text = "Oops. There was a problem"
}
return view
}
}
答案 0 :(得分:0)
您可以简单地在 toString
类中实现 Congregation
:
@kotlinx.serialization.Serializable
data class Congregation(
var id: Int,
var name: String,
var language: String
) {
override fun toString(): String {
return "$name ($language)"
}
}