我想检索选中的复选框的数量,这是我的尝试。
private int checkCheckBoxes(int total) {
View habitosView = (LayoutInflater.from(mContext)).inflate(R.layout.habitos_list_row, null);
CheckBox CB1 = habitosView.findViewById(R.id.CBdia1);
CheckBox CB2 = habitosView.findViewById(R.id.CBdia2);
CheckBox CB3 = habitosView.findViewById(R.id.CBdia3);
CheckBox CB4 = habitosView.findViewById(R.id.CBdia4);
CheckBox CB5 = habitosView.findViewById(R.id.CBdia5);
CheckBox[] checkBoxes = new CheckBox[5];
checkBoxes[0] = CB1;
checkBoxes[1] = CB2;
checkBoxes[2] = CB3;
checkBoxes[3] = CB4;
checkBoxes[4] = CB5;
int habitosTotal = total;
for (int x=0; x<5; x++){
if(checkBoxes[x].isChecked()){
habitosTotal = habitosTotal + 1;
}
}
Log.d("Habitos total" , habitosTotal+"");
return habitosTotal;
};
对于 View 的 OnClick,我有这个
public void onBindViewHolder(MyViewHolder holder, final int position){
holder.nombre.setText(mHabitosList.get(position).getNombre());
holder.habitosCardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int total = mHabitosList.get(position).getTotal();
checkCheckBoxes(total);
AppCompatActivity activity = (AppCompatActivity) view.getContext();
FragmentHabitos fragmentHabitos= new FragmentHabitos();
fragmentHabitos.setArguments(args);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentHabitos)
.addToBackStack(null).commit();
}
});
}
无论如何它都返回 0,谁能指出错误。我找不到它。
最佳答案
您应该使用 setOnCheckedChangeListener。
示例:
chk.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()){
case R.id.checkbox1:
if(isChecked)
//increment checked total
else
//dercrement checked total
break;
case R.id.checkBox2:
if(isChecked)
//increment checked total
else
//decrement checked total
break;
}
}
});
关于android - 选中复选框时添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50182866/