我正在尝试处理一个事件,如果该人选中所有复选框,则应该发生一个操作,即使按钮可单击。
到目前为止,我只能检查某个框是否已选中或未选中,但找不到一种方法来设置单击的复选框数量的计数器。
复选框将是动态的,但在此代码示例中,我仅使用静态值。
我尝试设置一个计数器,如果我单击一个复选框,它应该会增加,但无法找出正确的方法。
//我调用的方法
ArrayList<String> arrayList= new ArrayList<>();
arrayList.add("2Pac");
arrayList.add("Biggie");
arrayList.add("Nas");
// Create Checkbox Dynamically
for(int i=0;i<arrayList.size();i++) {
CheckBox checkBox = new CheckBox(getContext());
checkBox.setText(arrayList.get(i));
checkBox.setTextSize(20);
checkBox.setId(++checkBoxID);
checkBox.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// int counter = -1;
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
// String msg = "You have " + (isChecked ? "checked" : "unchecked") + " this box it Checkbox.";
//Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
if(checkBox.isChecked())
{
//Toast.makeText(getActivity(), ""+ counter, Toast.LENGTH_SHORT).show();
}else
{
// counter++;
// Toast.makeText(getActivity(), ""+ counter, Toast.LENGTH_SHORT).show();
}
}
});
for(int j=0;j<allCheckBox.size();j++)
{
if(allCheckBox.size()==arrayList.size())
{
//Toast.makeText(MainActivity.this, ""+ checkBox.getId(), Toast.LENGTH_SHORT).show();
}
}
// Add Checkbox to LinearLayout
if (linearLayout != null) {
linearLayout.addView(checkBox);
}
到目前为止,我已经花了一天多的时间来解决这个问题! 非常感谢任何帮助或想法。
最佳答案
在 for 循环外部定义计数器,初始值为 0,当用户选中复选框时将其增加 1,当用户取消选中复选框时将计数器减少 1,并且在相同的情况下 >onCheckedChanged 监听器检查像这样的复选框的数量
ArrayList<String> arrayList= new ArrayList<>();
arrayList.add("2Pac");
arrayList.add("Biggie");
arrayList.add("Nas");
int counter = 0; //all checkboxes unchecked
// Create Checkbox Dynamically
for(int i=0;i<arrayList.size();i++) {
CheckBox checkBox = new CheckBox(getContext());
checkBox.setText(arrayList.get(i));
checkBox.setTextSize(20);
checkBox.setId(++checkBoxID);
checkBox.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(checkBox.isChecked())
{
counter++;
if (counter == arrayList.size()) {
//make your button clickable here
}
} else {
counter--;
//disable your button incase the user uncheck one of the checkboxes after all checkboxes were checked
} //end if
}
});
// Add Checkbox to LinearLayout
if (linearLayout != null) {
linearLayout.addView(checkBox);
} //end if
} //end for
我是用手机写的代码,所以我没有测试代码 我希望它能起作用
关于java - 检查是否所有复选框均已选中。安卓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60540498/