在 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 中添加或刪除多選項了。