首页 > 解决方案 > Kotlin/Android - setOnClickListener 仅适用于一个按钮

问题描述

我有recyclerView多个项目(ViewHolders)。在其中一个(ViewHolderItemTratamentos)中,我得到了以下元素:

在此处输入图像描述

当单击第一个“添加按钮”时,通过充气机布局,相同的元素 (editTextbutton) 会在之前的元素下方创建。像这样:

在此处输入图像描述

到这里,一切正常。另一行是用一个 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>

标签: androidbuttonkotlinonclicklistenerlayout-inflater

解决方案


您使用对内部视图的合成引用来扩展视图的方式。我不确定它是否以这种方式工作,因为R它是在编译时创建的,而不是运行时创建的。我想你在 RecyclerView 中使用了多个这种类型的 ViewHolder。在这种情况下,相同的 ID 将被设置为多个视图,这是不可能的。

我的猜测是,这btn_add_field_din并没有参考您认为的观点。检查它。尝试设置背景Color.RED,看看这是否是正确的视图。

另外,removeField(btn_add_field_din, holder.parent_linear_layout)似乎删除了视图,是吗?


推荐阅读