Search code examples
kotlintextviewpopupwindow

Kotlin - Changing TextView content in popup layout from a different screen


I have this simple layout with a textview, that pops up when being clicked on an image in a different layout.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/popupHpPot"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:background="#000000">

    <TextView
        android:id="@+id/popupItemDesc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Potion that restores 3 health."
        android:textColor="#FFEB3B"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

This is the code snippet handling the popup:

 hpPotImg.setOnClickListener(){
            val window = PopupWindow(this)
            val view = layoutInflater.inflate(R.layout.item_popup_tooltip, null)
            window.contentView = view
            val popupLayout = view.findViewById<ConstraintLayout>(R.id.popupHpPot)
            popupLayout.setOnClickListener(){window.dismiss()}
            window.showAsDropDown(hpPotImg)

        }

How could I change the text from the view with "popupItemDesc" id from the setOnClickListener() snippet?


Solution

  • You will need to use findViewById method with the parent view popupLayout to get the child view of popupItemDesc as below

        val popupItemDesc = popupLayout.findViewById<TextView>(R.id.popupItemDesc)
    

    so the code will be like this

            hpPotImg.setOnClickListener(){
            val window = PopupWindow(this)
            val view = layoutInflater.inflate(R.layout.item_popup_tooltip, null)
            window.contentView = view
            
            val popupLayout = view.findViewById<ConstraintLayout>(R.id.popupHpPot)
            val popupItemDesc = popupLayout.findViewById<TextView>(R.id.popupItemDesc)
    
            popupItemDesc.text = "hello text changed in parent"
    
            popupLayout.setOnClickListener(){
                // you can use it here freely also
                popupItemDesc.text = "hello text changed in child popupItemDesc inside popup"
    
                window.dismiss()
            }
            window.showAsDropDown(hpPotImg)
        }