android - 如何在自定义适配器内生成的按钮中设置一些操作
问题描述
我得到了以下组成:
这个布局是我的一个项目RecyclerView.Adapter
。X 按钮 ( holder.delete_button
) 在单击时会删除自己和EditText
; 基本上它删除了行。
ADD FIELD 按钮添加新行(通过充气机):
这是添加新行的代码:
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)
}
}
我的问题是我只能删除第一行,因为这是我唯一可以在bybutton
中初始化的。但是对于接下来的 X 按钮,我不能不采取任何行动,因为它在外部布局中的按钮膨胀了,称为!我试图生成 id,但后来我不知道如何将它们放入数组中。这是删除一行的代码:ViewHolder
id
delete_button
generated_layout
holder.delete_button.setOnClickListener{
holder.parent_layout.removeView(holder.delete_button.parent as View)
}
这里也是 generate_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>
推荐阅读
- reactjs - React HighChart 示例
- c# - 在 C# WPF 中将某些文本复制到剪贴板时出错
- php - 如何在不呈现 httpException 页面的情况下使用 symfony 捕获异常
- python - 在 Geopandas 中进行交叉时出现 TopologyException 问题?
- delphi - 将带有证书处理的 2007 C++Builder SOAP 代码移至 Delphi2018-Indy10
- php - 带有 PayPal REST API 的信用卡
- sas - Proc Report - 两个表的行
- python - 芹菜任务未在部署在 Heroku 上的 Django 应用程序中执行
- reactjs - 在创建反应应用程序中使用两种不同类型的 React 导致反应错误(在未安装的组件上调用了 findDOMNode。)
- java - 商米V1s设备-打印机打印完成后Java回调不起作用