Question

I just started off with trying to get to know to Java in order to be able to write simple android apps. Right now I try to get in touch with "standard-controls", as my book says.

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
    cb.setOnCheckedChangeListener( new OnCheckedChangeListener(){
        public void onCheckedChanged(CompoundButton buttonView, 
            boolean isChecked)
        {
            TextView tv = (TextView) findViewById(R.id.textView1);
            if (isChecked){
                tv.setText("Checkbox is checked!!");}
            else {tv.setText("Checkbox is unchecked!!");}
        }
    });}

My GUI contains a TextView and a CheckBox object. I basically copied this code from my book. Nevertheless I more or less understand whats's going on. As far as I think, a procedure/method (called "onCheckedChanged) should be added as a subscriber to the event "OnCheckedChange" of my Checkbox. Unfortunately, I do not get when or where this procedure is called, because it has to get argument-objects, right? Up to now, the procedure only "knows" of which type the arguments should be. I seriously tried to figure this out but haven't made any progress for an hour or two. Thus, I'd absolutely appreciate it if anyone could help me out.

Was it helpful?

Solution

The system calls the onCheckedChanged() method for you and passes the arguments to the method whenever the check state changes for the CheckBox you have added the listener to. This is automatically handled by the system with the correct arguments (the CheckBox whose check state has changed and whether it is now checked or not) and you probably will never want to call onCheckedChanged() manually in your code.

You should be aware that you are not subscribing the method onCheckedChanged() directly to the event. You are actually creating an anonymous class that implements the onCheckedChangeListner interface and implementing that method in this class. You are passing in an instantiated object of this class to the setOnCheckedChangeListener() method.

Notice the onCreate() method that you are overriding in the code you posted. This is similar in that it is called by the system when creating an Activity object. Nowhere in your own code will you call onCreate() on an Activity object, it is a callback for you to override and add your code to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top