android - SearchView 不显示建议
问题描述
所以我想在searchView
现在位于工具栏中的 a 中显示一个建议。所以我创建了这个适配器,它似乎不起作用,应用程序也因为这个错误而崩溃StringIndexOutOfBoundsException
适配器
class SearchHitchAdapter(context: Context, cursor: Cursor) : CursorAdapter(context, cursor, false) {
private val dataSet = arrayListOf<String>(*context.resources.getStringArray(R.array.city_states))
override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
val inflater = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
return inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false)
}
override fun bindView(view: View?, context: Context?, cursor: Cursor?) {
val position = cursor!!.position
val textView = view!!.findViewById(android.R.id.text1) as TextView
textView.text = dataSet[position]
}
}
这个函数在里面被调用onQueryTextChange
private fun setUpSearchSuggestions(query: String) {
val dataSet = getCityList()
val columns = arrayOf("_id", "text")
val temp = arrayOf(0, "default")
val cursor = MatrixCursor(columns)
for (i in 0 until dataSet.size) {
val city = dataSet[i]
if (city.toLowerCase(Locale.US).contains(query.toLowerCase(Locale.US))) {
temp[0] = i
temp[1] = city[i]
cursor.addRow(temp)
}
}
searchVIew.suggestionsAdapter = SearchAdapter(context!!, cursor)
}
这是行不通的,有人可以帮助我或给我一些建议。
解决方案
您代码中的这一行看起来很可疑:
temp[1] = city[i]
这与写作相同temp[i] = city.get(i)
:您试图从city
at 位置获取角色i
。
由于i
是循环变量,并且您正在循环dataset
,这很可能是一个错误。不能保证数据集中的每个字符串都与数据集本身一样长。想象一下,您有一个包含一千个城市的列表;很有可能每个城市的名称都不到一千个字符。
推荐阅读
- python - 无法在 python 中解析来自 sg.media-imdb 的响应
- c++ - 无法将 'Class::operator==' 从类型 'bool (Class::)(Class*) 转换为类型 'bool
- angular - Angular 7 - 如何在提交后立即显示数据
- vue.js - 在 SSR Nuxtjs vue 中第二次将 asyncData() 与客户端数据绑定
- java - 如何使用 JPA 即 Hibernate EntityManager 解决“使用 Hibernate 内置连接池(不用于生产使用!)”
- python - 如何在熊猫表中删除重复项?
- python - 如何获取字符串末尾的总位数
- python - 在 Python 中使用 Schedule 进行多处理
- javascript - 在使用可观察的和使用异步的声明性方法测试角度组件时,获取 TypeError 管道不是一个函数
- postgresql - 使用带有 UUID 的 SQL“seek”在 PL/pgSQL 查询中进行排序