简体   繁体   English

在 position 在 Android 获取项目 ListVIew

[英]Get item at position at Android ListVIew

I am trying to retrieve data from the item I clicked but I always get null, I could not find a solution for this.我正在尝试从我单击的项目中检索数据,但我总是得到 null,我找不到解决方案。 My code:我的代码:

 override fun onStart() {
        super.onStart()

        val records = RecordDAO(this).findAll().map {
            "${it.moduleName} ${it.moduleNum} (%${it.noteInProzent} ${it.creditPoints}crp)"
        }

        val adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,records)

        this.recordListView.adapter = adapter

        recordListView.setOnItemClickListener { parent, view, position, id ->
            var record: Record? = recordListView.getItemAtPosition(position) as? Record
            if(record!= null) println(record.moduleName)
            else println("rec is null")
            intent = Intent(this,EditFormActivity::class.java)
            intent.putExtra("record",record)
            startActivity(intent)
        }
    }

Every time in the null check it prints null so I can not retrieve my item somehow, when I print the position for example I get the right position but I can not retrieve the item at that position. Every time in the null check it prints null so I can not retrieve my item somehow, when I print the position for example I get the right position but I can not retrieve the item at that position.

The records in your code are stored in the listView adapter, so in onItemClickListener, get your item from the adapter as shown below:您代码中的记录存储在 listView 适配器中,因此在 onItemClickListener 中,从适配器中获取您的项目,如下所示:

adapter.getItem(position)

Another approach could be:另一种方法可能是:

(typecast_into_respective_object) parent.getItemAtPosition(position)

Here parent is the adapterView object in setOnItemClickListener.这里的parent是setOnItemClickListener中的adapterView object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM