我的活动xml中有700个复选框。我需要获取所有选中复选框的文本。
一种方法是查看是否checkbox1 isChecked()
并获取文本,但是对700个复选框执行此操作过于重复。
答案 0 :(得分:0)
我认为最好的方法可能是,从一个空的String数组开始(表示选中的复选框为零)。每次选择一个复选框时,都将其文本添加到数组中,每次取消选中该复选框时,则从数组中删除该字符串(如果存在)。最后,您只需要循环数组即可获取选定的字符串
编辑:
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)
}
}
}