I got the following composition:
This layout is an Item of my RecyclerView.Adapter
. The X button (holder.delete_button
), when clicked, deletes himself and the EditText
; basically it removes the row.
The ADD FIELD button add new rows (by inflater):
Here's the code to add new line:
holder.add_field_button.setOnClickListener {
holder.parent_layout.apply {
val inflater = LayoutInflater.from(context)
val rowView = inflater.inflate(R.layout.generated_layout, this, false)
holder.parent_layout.addView(rowView, holder.parent_layout.childCount!! - 0)
}
}
My problem here is that I just can delete the first row, because is the only button
I can initialize in the ViewHolder
by the id
of delete_button
. But for the next X buttons, I can't do no action, because the button it's in an external layout inflated, called generated_layout
! I've tried to generate ids but then I don't know how to put them into an array. Here's the code to delete a row:
holder.delete_button.setOnClickListener{
holder.parent_layout.removeView(holder.delete_button.parent as View)
}
Here's the code of generated_layout, as well:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone"/>
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_weight="0"
android:background="@android:drawable/ic_delete"/>
</LinearLayout>
Set the onClick listener like this
holder.add_field_button.setOnClickListener {
holder.parent_layout.apply {
val inflater = LayoutInflater.from(context)
val rowView = inflater.inflate(R.layout.generated_layout, this, false)
val rowViewDeleteButton=rowView.findViewById(R.id.deletebutton)
rowViewDeleteButton.setOnClickListener{
holder.parent_layout.removeView(it.parent as View)
}
holder.parent_layout.addView(rowView, holder.parent_layout.childCount!! - 0)
}
}
And give id
to your delete button :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >
<EditText
android:id="@+id/text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone"/>
<Button
android:id="@+id/deletebutton"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_weight="0"
android:background="@android:drawable/ic_delete"/>
</LinearLayout>