Reputation: 155
I have some Checkbox (suppose 5) and one Button. When I clicked in the button, I want to show a toast message with total selected checkbox. How can I do that?
Upvotes: -4
Views: 1163
Reputation: 140
according to your question this could possibly be the answer to your question. hope this helps..if you could provide more information about your requirement we could help in much better way
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--;
}
}
}
Upvotes: 1
Reputation: 78
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);
}
});
Upvotes: -1