首页 > 技术文章 > Android ListView使用入门——Kotlin

cnwy 2020-10-13 14:59 原文

.xml

        <ListView
            android:id="@+id/lv_drvices"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

.kt

        val data = ArrayList<String>()
        var adapter: ArrayAdapter<String>? = null

                    data.add("AA")
                    data.add("BB")
                    adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,data)
                    lv_drvices.adapter = adapter

用法——设置点击方法,获取item的text值

        lv_drvices.setOnItemClickListener{ parent, view, position, id ->
            toast(lv_drvices.getItemAtPosition(position).toString())
        }

    private fun toast(string: String){
        Toast.makeText(applicationContext, string,
            Toast.LENGTH_SHORT).show()
    }

推荐阅读