我得到了以下组成:
此布局是我的RecyclerView.Adapter
的一个项目。单击 X 按钮 (holder.delete_button
) 会删除其自身和 EditText
;基本上它删除了行。
ADD FIELD 按钮添加新行(通过 inflater):
这是添加新行的代码:
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)
}
}
我的问题是我只能删除第一行,因为这是我唯一可以在ViewHolder
中初始化的按钮
delete_button
的 id
。 但是对于接下来的 X 个按钮,我不能不采取任何行动,因为按钮处于膨胀的外部布局中,称为 generated_layout
!我试图生成 id,但我不知道如何将它们放入数组中。下面是删除一行的代码:
holder.delete_button.setOnClickListener{
holder.parent_layout.removeView(holder.delete_button.parent as View)
}
这里还有 generated_layout 的代码:
<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>
最佳答案
像这样设置onClick监听器
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)
}
}
并将 id
给你的删除按钮:
<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>
关于android - 如何在自定义适配器内生成的按钮中设置一些 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54132100/