Search code examples
androidkotlinandroid-listviewandroid-arrayadapterandroid-adapter

Kotlin ListView item click based on String


Is there a way to check which string was clicked within a simple ListView? I want something different to happen for each item in this ListView (when clicked) but I've not seen any relevant/helpful tutorials. I understand that a when block would be necessary for this but unsure of the best way to implement it.

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>

Solution

  • Inside onItemClick(), the position parameter is the position in the data set that was tapped. So you ought to be able to index into your array to get the tapped string:

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

    If you want to verify that the clicked item has a certain value, you can similarly do this:

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