首页 > 解决方案 > 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)
    }

这是行不通的,有人可以帮助我或给我一些建议。

标签: androidkotlinsearchview

解决方案


您代码中的这一行看起来很可疑:

temp[1] = city[i]

这与写作相同temp[i] = city.get(i):您试图从cityat 位置获取角色i

由于i是循环变量,并且您正在循环dataset,这很可能是一个错误。不能保证数据集中的每个字符串都与数据集本身一样长。想象一下,您有一个包含一千个城市的列表;很有可能每个城市的名称都不到一千个字符。


推荐阅读