基于String的Kotlin ListView项目点击

Kotlin ListView item click based on String

有没有办法检查在简单的 ListView 中单击了哪个字符串?我希望此 ListView(单击时)中的每个项目发生不同的事情,但我没有看到任何 relevant/helpful 教程。我知道为此需要一个 when 块,但不确定实现它的最佳方法。

class MainActivity : AppCompatActivity() {

    var array = arrayOf("Melbourne", "Vienna", "Vancouver", "Toronto", "Calgary", "Adelaide", "Perth", "Auckland", "Helsinki", "Hamburg", "Munich", "New York", "Sydney", "Paris", "Cape Town", "Barcelona", "London", "Bangkok")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val adapter = ArrayAdapter(this,
                R.layout.listview_item, array)

        val listView:ListView = findViewById(R.id.listview_1)
        listView.setAdapter(adapter)

        listView.onItemClickListener = object : OnItemClickListener {

            override fun onItemClick(parent: AdapterView<*>, view: View,
                            position: Int, id: Long) {
                    ????
            }
        }

    }
} 

listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/relativelayout_listitem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="top"
    android:baselineAligned="false"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView android:id="@+id/listitem_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:ellipsize="marquee"
        android:layout_below="@id/ll_title"
        android:fadingEdge="horizontal" />
</RelativeLayout>

onItemClick()里面,position参数是数据集中被点击的位置。所以你应该能够索引到你的数组中以获取点击的字符串:

val tappedString = array[position] // will be "Vienna" when position is 1

如果你想验证点击的项目是否有一定的价值,你可以类似地这样做:

if (array[position] == "Vienna") {
    // ...
}

如果您不想使用 positionarray,那么您可以从视图中获取文本。

试试这个:

override fun onItemClick(parent: AdapterView<*>, view: View,
                        position: Int, id: Long) {
    val textClicked = view.findViewById<TextView>(R.id.listitem_title).text.toString()
    when (textClicked) {
        "something1" -> TODO()
        "something2" -> TODO()
    }
}