Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically set event listener on textview included in linearLayout

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <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>

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading