我在一项活动中有一些复选框(假设为5)和一个按钮。当我单击按钮时,“吐司”显示我选择了多少复选框。
答案 0 :(得分:1)
根据您的问题,这可能是您问题的答案。希望能对您有所帮助。
private CheckBox one, two, three, four, five;// checkboxes you want
Button btn;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
one=findViewById(R.id.one);
two=findViewById(R.id.two);
three=findViewById(R.id.three);
four=findViewById(R.id.four);
five=findViewById(R.id.five);
btn=findViewById(R.id.btn);
one.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedOrNot(isChecked);
}
});
two.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedOrNot(isChecked);
}
});
three.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedOrNot(isChecked);
}
});
four.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedOrNot(isChecked);
}
});
five.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedOrNot(isChecked);
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), count + " checkbox checked", Toast.LENGTH_SHORT).show();
}
});
}
private void isCheckedOrNot(boolean isChecked) {
if (isChecked) {
count++;
} else {
if (count > 0) {
count--;
}
}
}
答案 1 :(得分:-1)
btn = findViewById(R.id.btn);
rb = findViewById(R.id.rb); // make 5 of them
int x=0;
rb.setOnClickListener(new View.OnClickListener() { // make 5 of them
@Override
public void onClick(View v) {
boolean checked = ((RadioButton) v).isChecked();
// Check which radiobutton was pressed
if (checked){
x++;
}
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(x);
}
});