ExposedDropdownMenu 中字符串以外的其他对象
Other objects than strings in ExposedDropdownMenu
我想使用 MaterialDesign 文档中指定的 AutoCompleteTextView
(连同 TextInputLayout
)作为公开的下拉菜单。是否可以使用自定义对象?所以我可以用 getSelectedItem
?
之类的东西检索选定的对象
MD 文档:https://material.io/components/menus/android#exposed-dropdown-menus
Is it possible to use custom objects with it?
是的,你可以。
假设您正在创建用户公开的下拉菜单:
data class User(val id: String, val name: String) {
override fun toString(): String {
return name
}
}
创建列表项布局:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:padding="16dp"
android:textAppearance="?attr/textAppearanceSubtitle1" />
创建您的适配器:
val adapter = ArrayAdapter<User>(context, R.layout.list_item_user, emptyList())
autoCompleteTextView.setAdapter(arrayAdapter)
autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
val selectedTeam: User? = arrayAdapter.getItem(position)
}
就是这样。快乐编码! :)
我想使用 MaterialDesign 文档中指定的 AutoCompleteTextView
(连同 TextInputLayout
)作为公开的下拉菜单。是否可以使用自定义对象?所以我可以用 getSelectedItem
?
MD 文档:https://material.io/components/menus/android#exposed-dropdown-menus
Is it possible to use custom objects with it?
是的,你可以。
假设您正在创建用户公开的下拉菜单:
data class User(val id: String, val name: String) {
override fun toString(): String {
return name
}
}
创建列表项布局:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:padding="16dp"
android:textAppearance="?attr/textAppearanceSubtitle1" />
创建您的适配器:
val adapter = ArrayAdapter<User>(context, R.layout.list_item_user, emptyList())
autoCompleteTextView.setAdapter(arrayAdapter)
autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
val selectedTeam: User? = arrayAdapter.getItem(position)
}
就是这样。快乐编码! :)