首页 > 解决方案 > 获取选定的几个复选框的文本android?

问题描述

我的活动 xml 中有 700 个复选框。我需要获取所有选定复选框的文本。

一种方法是查看 checkbox1isChecked()并获取文本,但是对 700 个复选框执行此操作过于重复。

标签: android

解决方案


我认为最好的方法可能是从一个空的字符串数组开始(代表选中的零个复选框)。每次选择复选框时,将其文本添加到数组中,每次取消选中复选框时,从数组中删除该字符串(如果存在的话)。最后,您只需要循环数组即可获取选定的字符串

编辑:

class MainActivity : AppCompatActivity(), CompoundButton.OnCheckedChangeListener {

private lateinit var checkbox1: CheckBox
private lateinit var checkbox2: CheckBox
private lateinit var checkboxContainer: ConstraintLayout
private var checkedStrings = ArrayList<String>()

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    checkbox1 = findViewById(R.id.checkbox1)
    checkbox2 = findViewById(R.id.checkbox2)
    checkboxContainer = findViewById(R.id.checkboxContainer)

    checkbox1.setOnCheckedChangeListener(this)
    checkbox2.setOnCheckedChangeListener(this)

    //or, if you have the checkboxes statically added to your layout, which I suspect you do, you can loop through the view like:
    for (i in 0..checkboxContainer.childCount){
        if (checkboxContainer.getChildAt(i) is CheckBox){
            (checkboxContainer.getChildAt(i) as CheckBox).setOnCheckedChangeListener(this)
        }
    }
}

override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {

    val checkBoxString = (buttonView as CheckBox).text.toString()

    if (isChecked){
        checkedStrings.add(checkBoxString)
    }else{
        checkedStrings.remove(checkBoxString)
    }
}

fun processStrings(){

    // at the end of the iteration/screen/whatever you can check the content of the checkedStrings array like, for instance:

    for (string in checkedStrings){
        Log.e("print string", string)
    }
}
}

推荐阅读