Search code examples
androidkotlinandroid-recyclerviewadapterandroid-viewholder

Kotlin/Android - Get the id of generated button inside onBindViewHolder Item


I got a recyclerView with multiple items (ViewHolders). In one (ViewHolderItemTratamentos) of these I got the following elements:

enter image description here

When the first "add button" is clicked, through an inflator layout, the same elements (editText and button) are created beneath the previous ones. Just like this:

enter image description here The code from my adapter (which got the logic of the set click) which create the new line:

holder.add_field_button.setOnClickListener {
    holder.parent_linear_layout.apply {
        val inflater = LayoutInflater.from(context)
        val rowView = inflater.inflate(R.layout.used_products_field, this, false)
        holder.parent_linear_layout.addView(rowView, holder.parent_linear_layout.childCount!! - 0)
        holder.add_field_button.text = "-"
     }
  }

So, the problem is that I can't get the id from the button of the layout.used_products_field to generate another new line. Should I inflate this layout (It does make any sense?)? And should I give the same id to every button (static and the generated one)?

Content of the R.layout.used_products_field:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
    android:id="@+id/number_edit_text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="phone"/>

<Button
    android:id="@+id/add_field_button"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    style="@style/botaoCard"
    android:textSize="24dp"
    android:text="+"
    android:padding="5dp"/>


Solution

  • You can get the views inside the inflated layout (used_products_field)

    val inflater = LayoutInflater.from(context)
    val rowView = inflater.inflate(R.layout.used_products_field, this, false)
    val button = rowView.findViewById<Button>(R.id.add_field_button)
    val edittext = rowView.findViewById<EditText>(R.id.number_edit_text)