RadioGroup and checkedId

778 views Asked by At

I just start my learning last week, I have some questions about the RadioGroup on my book.


radioGroup.clearCheck();

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);

                switch (rb.getId()) {

                    case R.id.radioButtonLondon:
                        tClock.setTimeZone("Europe/London");
                        break;

                    case R.id.radioButtonBeijing:
                        tClock.setTimeZone("CST6CDT");
                        break;


                    case R.id.radioButtonNewYork:
                        tClock.setTimeZone("America/New_York");
                        break;
                }
                // End switch block

            //}
        }
    });

  1. On my book it says RadioButton rb = (RadioButton) group.findViewById(checkedId);is used to

"get a reference to the actual object that checkedId is referring to, then we can retrieve the familiar ID that we use for the currently selected radio button, for which we now have a reference stored in rb."

I'm very confused about this explaination

  1. Is this line RadioButton rb = (RadioButton) group.findViewById(checkedId); necessary? I tried to hide this line and change switch (rb.getId()) to switch(checkedId) and everything still working fine.

Thank you!

2

There are 2 answers

0
Saurabh Padwekar On BEST ANSWER

Dont define the radiobutton.In setOnCheckedChangeListener itself you will get the radio button id.Remove RadioButton rb = (RadioButton) group.findViewById(checkedId);

Your code should look like this :

 radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

            switch (checkedId) {

                case R.id.radioButtonLondon:
                    tClock.setTimeZone("Europe/London");
                    break;

                case R.id.radioButtonBeijing:
                    tClock.setTimeZone("CST6CDT");
                    break;


                case R.id.radioButtonNewYork:
                    tClock.setTimeZone("America/New_York");
                    break;
            }
            // End switch block

        //}
    }
});
0
Emmagency On

Seeing that you're only updating "tClock" then you're right about that line not being necessary. That would have been necessary if for some other reason, you needed to call any of the available methods for radio buttons.