Android SearchView不显示建议
因此,我想在Android SearchView不显示建议,android,kotlin,searchview,Android,Kotlin,Searchview,因此,我想在searchView中显示一个建议,它现在位于工具栏中。因此,我创建了这个适配器,但它似乎不起作用,应用程序也因此错误而崩溃StringIndexOutOfBoundsException 适配器 class SearchHitchAdapter(context: Context, cursor: Cursor) : CursorAdapter(context, cursor, false) { private val dataSet = arrayListOf<Str
searchView
中显示一个建议,它现在位于工具栏中。因此,我创建了这个适配器,但它似乎不起作用,应用程序也因此错误而崩溃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]
}
}
这不起作用。有人可以帮我或给我一些建议。异常“StringIndexOutOfBoundsException”表示您正在访问不存在的数据。检查数据集的列表是否正确。代码中的这一行看起来可疑: 这与写入
temp[i]=city.get(i)
相同:您试图从city
的i
位置获取字符
由于
i
是循环变量,并且您正在dataset
上循环,这很可能是一个错误。不能保证数据集中的每个字符串都和数据集本身一样长。想象一下,你有一张一千个城市的清单;很有可能每个城市的名称长度都少于1000个字符。是的,我在同一行得到了错误。但为什么我不明白。如果代码包含字符串,则将其添加到光标中。如果我在做这个temp[1]=city
,那么所有列表都会显示在建议中。那么,它现在所做的是将城市名称的I
-第个字符添加到光标中。如果只使用城市
,则会将城市名称添加到光标中。
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]