Kotlin以编程方式创建复选框和删除复选框

时间:2018-10-31 11:01:26

标签: android kotlin

当我勾选现有复选框时,我可以动态添加复选框,但是当我取消勾选现有复选框时,似乎无法删除新复选框。

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

            }

1 个答案:

答案 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) {
        }
    }
}