android - Kotlin/Android - setOnClickListener 仅适用于一个按钮
问题描述
我有recyclerView
多个项目(ViewHolders
)。在其中一个(ViewHolderItemTratamentos)中,我得到了以下元素:
当单击第一个“添加按钮”时,通过充气机布局,相同的元素 (editText
和button
) 会在之前的元素下方创建。像这样:
到这里,一切正常。另一行是用一个 equaleditText
和一个 equal创建的,button
它有一个不同的 id,R.id.btn_add_field_din
(来自膨胀的布局)。这button
在这里得到了相同的逻辑。它膨胀了相同的布局(同一行)。但是,这第三个按钮不起作用,它得到了相同的 id ( R.id.btn_add_field_din
)。我也试过了tag
,但它给了我同样的问题。
问题是我想要有很多行,但是从第三个按钮开始就setClickOnListener
丢失了 action。你知道可能是什么吗?这是代码:
适配器:
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 = "-"
//remove row
removeField(holder.add_field_button, holder.parent_linear_layout)
btn_add_field_din.setOnClickListener {
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)
btn_add_field_din.text = "-"
//remove row
removeField(btn_add_field_din, holder.parent_linear_layout)
}
}
}
布局充气(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:focusedByDefault="true"
android:inputType="phone"/>
<Button
android:id="@+id/btn_add_field_din"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
style="@style/botaoCard"
android:textSize="24dp"
android:text="+"
android:padding="5dp"/>
</LinearLayout>
解决方案
您使用对内部视图的合成引用来扩展视图的方式。我不确定它是否以这种方式工作,因为R
它是在编译时创建的,而不是运行时创建的。我想你在 RecyclerView 中使用了多个这种类型的 ViewHolder。在这种情况下,相同的 ID 将被设置为多个视图,这是不可能的。
我的猜测是,这btn_add_field_din
并没有参考您认为的观点。检查它。尝试设置背景Color.RED
,看看这是否是正确的视图。
另外,removeField(btn_add_field_din, holder.parent_linear_layout)
似乎删除了视图,是吗?
推荐阅读
- sql-server - SQL Server 2008 透视和连接
- javascript - 从 Brightspace 上的 API 获取字段
- python - python中的高效IP扫描器
- c# - 在不同的、独立的对象上工作的 C# 任务,仍然会出现同步错误,为什么?
- react-native - 在图标旁边的 FlatList 中居中文本 - React Native
- c - 可以覆盖指向字符串的指针数组的值吗?
- ios - Swift:在从初始化程序返回之前,不会在所有路径上调用“super.init”?
- php - 推荐奖金计算两次
- javascript - firebase 和 Angular 7 中文档中的集合
- width - Fabric.js:以编程方式更新其尺寸后未渲染的部分 Line