【问题标题】:Get item at position at Android ListVIew在 Android ListVIew 的位置获取项目
【发布时间】:2021-03-10 17:11:09
【问题描述】:

我正在尝试从我单击的项目中检索数据,但我总是得到空值,我找不到解决方案。我的代码:

 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)
        }
    }

每次在 null 检查中它都会打印 null,因此我无法以某种方式检索我的项目,例如当我打印位置时,我得到了正确的位置,但我无法在该位置检索项目。

【问题讨论】:

    标签: android kotlin android-listview


    【解决方案1】:

    您代码中的记录存储在listView适配器中,因此在onItemClickListener中,从适配器中获取您的项目,如下所示:

    adapter.getItem(position)
    

    另一种方法可能是:

    (typecast_into_respective_object) parent.getItemAtPosition(position)
    

    这里parent是setOnItemClickListener中的adapterView对象。

    【讨论】:

    • 这会返回一个字符串?
    • 这将返回适配器正在存储的对象的类型。如果适配器正在存储字符串列表,那么它将返回一个字符串对象。
    • 不是存储记录吗?
    • 是的,所以它会返回“记录”类型的对象
    猜你喜欢
    • 2014-09-08
    • 2015-02-16
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 2013-09-08
    相关资源
    最近更新 更多