androidkotlinevent-listener

Kotlin set one listener for multiple controls


I'm approaching to kotlin (and to mobile coding) I'm trying to set one listener to run the same function on click on everyone of multiple textView. I found the below code on SO (sorry for missing link: I was unable to find it again) but i get error on the last "it", when I try to pass the textView to the function.

    val txtV_Ans1 = findViewById(R.id.txtV_Aswer1) as TextView
    val txtV_Ans2 = findViewById(R.id.txtV_Aswer2) as TextView
    val txtV_Ans3 = findViewById(R.id.txtV_Aswer3) as TextView
    val txtV_Ans4 = findViewById(R.id.txtV_Aswer4) as TextView

    val txtVs_Ans = arrayListOf(
        txtV_Ans1,
        txtV_Ans2,
        txtV_Ans3,
        txtV_Ans4
    )
    txtVs_Ans.forEach { it.setOnClickListener { txtV_Fill(it, "You clicked here")} }

fun txtV_Fill(txtV: TextView, txtToInsert: String){
    txtV.text = txtToInsert
}

Solution

  • The code you provided seems mostly correct, but you're encountering an issue because the it reference within the forEach lambda doesn't refer to a TextView in this context. You should use a more explicit approach to pass the TextView to the txtV_Fill function.

    val txtV_Ans1 = findViewById(R.id.txtV_Aswer1) as TextView
    val txtV_Ans2 = findViewById(R.id.txtV_Aswer2) as TextView
    val txtV_Ans3 = findViewById(R.id.txtV_Aswer3) as TextView
    val txtV_Ans4 = findViewById(R.id.txtV_Aswer4) as TextView
    
    val txtVs_Ans = arrayListOf(
        txtV_Ans1,
        txtV_Ans2,
        txtV_Ans3,
        txtV_Ans4
    )
    
    txtVs_Ans.forEach { txtView ->
        txtView.setOnClickListener { 
            txtV_Fill(txtView, "You clicked here")
        }
    }
    
    fun txtV_Fill(txtV: TextView, txtToInsert: String) {
        txtV.text = txtToInsert
    }