Reputation: 605
I am creating this activity that I request the user to find the correct answer using check boxes. My layout has multiple checkboxes but one of them is correct one. The main idea is to give a user 3 tries to guess the correct answer( the one checkbox). I manage to implement a code that when the correct checkbox is clicked to do something, but I can't get the code to work when user is clicking on any other checkbox.
My code is below (currently implemented the correct checkbox, but code for any other checkbox does not work) UPDATE
CheckBox centerBack, checkBox1;
int counts = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tennis_facts);
CheckBox centerBack = (CheckBox) findViewById(R.id.centerBack);
CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
centerBack.setOnClickListener(this);
checkBox1.setOnClickListener((this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.centerBack:
Toast.makeText(getApplicationContext(), "correct", Toast.LENGTH_SHORT).show();
break;
case R.id.checkBox1:
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_SHORT).show();
break;
}
}
Upvotes: 1
Views: 290
Reputation: 133
You mean these code below do not work, right ?
else{
counts ++;
DisplayToast("Incorrect Answer" + counts);
}
because you set listener for only this checkbox by code :
checkBox.setOnClickListener(new View.OnClickListener());
Others checkbox not set setOnClickListener yet. it a reason why when others checkbox checked, Android did not get this event
Should do:
checkBox.setOnClickListener(this);
checkBox2.setOnClickListener(this);
checkBox3.setOnClickListener(this);
checkBox4.setOnClickListener(this);
And You also should implement OnClickListener interface and override onClick method like this below :
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.checkBox:
//your code:
break;
case R.id.checkBox2:
//your code:
break;
case R.id.checkBox3:
//your code:
break;
case R.id.checkBox4:
//your code:
break;
}
}
Upvotes: 1
Reputation: 5096
Try to imlement View.OnClickListener interface in your Activity. then add to every chechkBox:
checkBox.setOnClickListener(this);
Inside the onClick:
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.checkBox1:
//your code:
break;
case R.id.checkBox2:
//your code:
break;
//so on...
}
}
Upvotes: 0