Search code examples
androidonclicklistenerandroid-buttonandroid-radiobuttononcheckedchanged

The difference between a Button and a RadioGroup in referencing


In an android Activity class, I saw the bridging to a Button of XML file and the setting it for click listener was using findViewById():

public class MyClass1 extends Activity implements OnClickListener {

    Button b;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo);

        b = (Button) findViewById(R.id.button1);    //This is where I have question
        b.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:

            break;
        case R.id.button2:

            break;
        }
    }
}

But As for referencing a RadioGroup (In another Activity class), It wasn't pointed to the Object by the findViewById() as it was for the Button:

public class MyClass2 extends Activity implements OnCheckedChangeListener {

    RadioGroup rg;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo);

        //Why isn't this here? --> rg = (RadioGroup) findViewById(R.id.radiogroup);
        rg.setOnCheckedChangeListener(this);
    }

   @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO Auto-generated method stub
        switch (checkedId) {
        case R.id.rBad:

            break;
        case R.id.rGood:

            break;
        }
    }
}

I mean in both onClick() and onCheckedChanged() methods the id of objects is referenced to.

So why b = (Button) findViewById(R.id.button1); is declared in the first code snippt, while the rg = (RadioGroup) findViewById(R.id.radiogroup); isn't in the second snippet.

Is it something related to RadioGroup or it's applicable to other objects too?


Solution

  • The RadioGroup example shouldn't even run, because the rg variable is never assigned and thus creates a NullPointerException when you try to set the onCheckedChanged listener. Essentially there should be no differences with the usage of the Button and RadioGroup classes, at least in this regard. This is more a pure Java thing than an Android specific subject.

    What you may have possibly stumbled upon is defining the listeners in the XML code, as in this StackOverflow answer. However, this doesn't directly work for the onCheckedChanged so it's weird that the situation here is this way around...

    Edit:

    Quoted from Adam S: Note there are view injection libraries such as ButterKnife which avoid the need for this, but your example here doesn't include any of the code required for that.

    However, it seems that the tutorial from which the code was taken had a bug in it.