如何从ListView setOnItemClickListener获取项目值?

2022-01-29 10:05:55 标签 androidkotlinlistviewarraylistbaseadapter

Listview setOnItemClickListener在getItemAtPosition中给出项目位置而不是给出值。whb单击Listview项目,然后给出错误:java。lang。ClassCastException: java。lang。Integer不能转换为java。lang。String。我会在。tostring之后,它会给出整数值。因此如何获得项目的价值列表视图项目。

代码

listView.setOnItemClickListener { parent, view, position, id ->
     val query : String = parent.getItemAtPosition(position) as String
     searchView?.setQuery(query,true)
}

使用BaseAdapter创建自定义ListView。

SearchAdapter。kt

class SearchAdapter(val searchList : ArrayList<Search>, val context: Context) : BaseAdapter() {
        override fun getCount(): Int {
            return searchList.size
        }
    
        override fun getItem(position: Int): Any {
            return position
        }
    
        override fun getItemId(position: Int): Long {
            return position.toLong()
        }
    
        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    
            val convertView = LayoutInflater.from(context).inflate(R.layout.textview_list,parent,false)
            val image = convertView.findViewById<ImageView>(R.id.imageViewHistory)
            val textView = convertView.findViewById<TextView>(R.id.text_list_view)
            val imageClear = convertView.findViewById<ImageView>(R.id.imageViewClear)
            val search = searchList.get(position)
            image.setImageResource(R.drawable.ic_baseline_search_24)
            textView.text = search.search
    
            return convertView
        }
    }

# # # SearchAdapter:

 override fun getItem(position: Int): Any {
      return searchList.get(position)
 }

在setOnItemClickListener:

 val search = parent.getItemAtPosition(position) as Search
 val query = search.query
阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码