选中所有复选框.android



我正在尝试处理一个事件,如果人员选中所有复选框,则应该执行一个操作,即使按钮可点击。

到目前为止,我只能检查一个复选框是选中还是未选中,但找不到一种方法来设置点击了多少复选框的计数器。

复选框将是动态的,但在这个代码示例中,我只使用了静态值。

我试着设置一个计数器,如果我点击一个复选框,它应该递增,但找不到正确的方法。

//我称之为的方法

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);
}

到目前为止,我已经花了一天多的时间试图弄清楚这一点!!任何帮助或想法都将不胜感激。

在初始值为0的for循环外定义计数器,当用户选中复选框时将其增加一,当用户取消选中复选框后将计数器减少一,并且在相同的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

我用手机写代码,所以没有测试代码我希望它能起作用

最新更新