Home > OS >  Dynamically set event listener on textview included in linearLayout
Dynamically set event listener on textview included in linearLayout

Time:09-27

I want to set an event listener that dynamically outputs the text of the textview to the textview included in the linearLayout. But I can't access the text property.

kotlin file

package com.jym.qb

class PrintActivity : AppCompatActivity() {



class PrintActivity : AppCompatActivity() {

    private val vBinding by lazy { ActivityPrintBinding.inflate(layoutInflater)}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)

        for(item in vBinding.optionLayout.children){
            item.setOnClickListener{
                Log.d("test", it.toString())
            }
        }
    }
}

layout File

    <LinearLayout
        android:id="@ id/optionLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@ id/option0"
            tools:text="option0" />

        <TextView
            android:id="@ id/option1"
            tools:text="option1" />

        <TextView
            android:id="@ id/option2"
            tools:text="option2" />

    </LinearLayout>

CodePudding user response:

Because the children are View (optionLayout.children), not a TextView, you have to cast:

        for(item in vBinding.optionLayout.children){
            if (item is TextView) {
                item.setOnClickListener{
                    Log.d("test", it.text)
                }
            }
        }

In this case you know for sure the children's are View but the method getChildren() from a ViewGroup returns a list of all the child as a generic View

  • Related