android - 获取选定的几个复选框的文本android?
问题描述
我的活动 xml 中有 700 个复选框。我需要获取所有选定复选框的文本。
一种方法是查看 checkbox1isChecked()
并获取文本,但是对 700 个复选框执行此操作过于重复。
解决方案
我认为最好的方法可能是从一个空的字符串数组开始(代表选中的零个复选框)。每次选择复选框时,将其文本添加到数组中,每次取消选中复选框时,从数组中删除该字符串(如果存在的话)。最后,您只需要循环数组即可获取选定的字符串
编辑:
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)
}
}
}
推荐阅读
- vue.js - Vuex:添加项目后,Vuetify 扩展面板插槽不会更新
- javascript - JSON 被错误解析
- python - 如何根据值更改 Excel 单元格颜色?
- jestjs - 开玩笑 - 在 beforeEach 完成之前执行测试
- c# - 如何从 C# 中的 TimePicker(WPF) 获取价值?
- c# - C# 重写静态方法
- matlab - 使用了“drawnow”,但在脚本结束之前无法使用菜单栏
- angular - 带有@input属性的Angular 7 2路绑定
- powershell - 如何使用 Win32_UserAccount 重命名方法?
- google-cloud-platform - 通过 Terraform 提供具有静态 IP 的 GCP VM 实例