在 Android 中,要实现一个可以动态增删多选项的视图,可以使用 RecyclerView 和相关的 Adapter。以下是一个简单的示例:
data class Option(val id: Int, val text: String, var isSelected: Boolean = false)
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Option Text" />
</LinearLayout>
class OptionsAdapter(private val options: MutableList<Option>) :
RecyclerView.Adapter<OptionsAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val checkbox: CheckBox = itemView.findViewById(R.id.checkbox)
val textView: TextView = itemView.findViewById(R.id.textView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.option_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val option = options[position]
holder.checkbox.isChecked = option.isSelected
holder.textView.text = option.text
holder.itemView.setOnClickListener {
option.isSelected = !option.isSelected
holder.checkbox.isChecked = option.isSelected
}
}
override fun getItemCount(): Int = options.size
}
val options = mutableListOf<Option>()
// 添加初始选项
options.add(Option(1, "Option 1"))
options.add(Option(2, "Option 2"))
options.add(Option(3, "Option 3"))
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
val adapter = OptionsAdapter(options)
recyclerView.adapter = adapter
val addButton: Button = findViewById(R.id.addButton)
val removeButton: Button = findViewById(R.id.removeButton)
addButton.setOnClickListener {
val newOption = Option(options.size + 1, "New Option ${options.size + 1}")
options.add(newOption)
adapter.notifyItemInserted(options.size - 1)
}
removeButton.setOnClickListener {
if (options.isNotEmpty()) {
options.removeAt(options.size - 1)
adapter.notifyItemRemoved(options.size)
}
}
这样,你就可以通过点击 “添加” 和 “删除” 按钮来动态地向 RecyclerView 中添加或删除多选项了。