android onCheckedChanged for radiogroup

user2534310 picture user2534310 · Aug 30, 2013 · Viewed 70.7k times · Source

I'm writing an Activity in android where I have two radio buttons under a RadioGroup. One of them is checked by default. But I can't trigger the event in onCreate method so that I can do something in that. The onCheckedChanged is running fine when clicked on.

RadioGroup ItemtypeGroup = (RadioGroup) findViewById(R.id.rechargeItemtype);
    RadioButton providerRadio = (RadioButton) findViewById(R.id.a);
    providerRadio.performClick();

    ItemtypeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged (RadioGroup group,int checkedId){

            Log.d("chk", "id" + checkedId);

            if (checkedId == R.id.a) {
                //some code
            } else if (checkedId == R.id.b) {
                //some code
            }
        }
    });

Answer

danny117 picture danny117 · Aug 30, 2013

To fire a radio check box for the default when initializing. Set everything to unchecked with the clearCheck method, then set the handler, then set the default and your handler will fire.

itemtypeGroup.clearCheck();

then same as usual add a listener...

itemtypeGroup
        .setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("chk", "id" + checkedId);

                if (checkedId == R.id.a) {
                    //some code
                } else if (checkedId == R.id.b) {
                    //some code
                }

            }

        });

Then check the default radio button and your listener will fire.

rb = (RadioButton) view.findViewById(R.id.a);
rb.setChecked(true);

Good Luck