public class CheckBoxDemo extends Activity implements
CompoundButton.OnCheckedChangeListener {
CheckBox cb;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
cb=(CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
cb.setText(R.string.checked);
}
else {
cb.setText(R.string.unchecked);
}
}
}
What I’m having trouble in understanding is how exactly this line works with this parameter being passed in
cb.setOnCheckedChangeListener(this);
Also, the method onCheckedChanged is not being explicitly called anywhere, how does Android make the connection to connect the checkbox state to the method name.
You are implementing the interface and
onCheckedChanged()is in your code. Your Activity now is also the Listener.When you implement an interface, you also have to override the methods specified by the interface. This means that the class that implements the interface can now act as an instance of that interface.
Your
CheckBoxDemoclass implementsOnCheckedChangeListenerso it can now act as anOnCheckedChangeListenerif it is needed.Then later in your code you have
Which is the method from the interface that
CheckBoxDemoneeds to implement for everything to work.Therefore, you can now use
this(refering to your currentCheckBoxDemoinstance) to pass off tosetOnCheckedChangeListener ()because all the prior conditions are met – Your Class can now successfully listen for check events.For more information, read up on Interfaces from the java tutorials.