当我勾选现有复选框时,我可以动态添加复选框,但是当我取消勾选现有复选框时,似乎无法删除新复选框。
baseCheckBox.setOnClickListener(View.OnClickListener {
val linearLayout = findViewById(R.id.newLinearLayout) as LinearLayout
if(baseCheckBox.isChecked){
val newBox= CheckBox(this)
newBox.text = "New CheckBox"
newBox.isChecked = true
linearLayout.addView(newBox)
}
else{
val tempLayout = findViewById(1) as LinearLayout
}
答案 0 :(得分:0)
一种实现方法是将对新创建的Checkbox
的引用存储在baseCheckBox
的标记中,这样就可以获取并删除它:
baseCheckBox.setOnClickListener{
val linearLayout = findViewById<LinearLayout>(R.id.newLinearLayout)
if (baseCheckBox.isChecked) {
val newBox = CheckBox(this)
newBox.text = "New CheckBox"
newBox.isChecked = true
linearLayout.addView(newBox)
baseCheckBox.setTag(newBox)
} else {
try {
val cb = baseCheckBox.tag as CheckBox
linearLayout.removeView(cb)
baseCheckBox.tag = null
} catch (e: Exception) {
}
}
}