Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In android, onCheckedChanged of a Radiogroup is not triggered when I Programmatically set a Radiobutton by call setChecked(true)

Tags:

android

In my application, I need to programmatically set a radiobutton and expect the onCheckedChanged of a Radiogroup to be triggered so that I can do something in it.

Code to set a radiobutton programmatically.

 LayoutInflater inflater = LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
 View view = inflater.inflate(R.layout.footer, null);
 RadioButton btn = (RadioButton)view.findViewById(R.id.footer_btn_course);
 btn.setChecked(true);

And in another activity, I did something like:

 public class MainActivity extends ActivityGroup implements RadioGroup.OnCheckedChangeListener{
      protected void onCreate(Bundle savedInstanceState){
            mRadioGroup = (RadioGroup)findViewById(R.id.footer_radio);
            mRadioGroup.setOnCheckedChangeListener(this);
      }

      @Override
      public void onCheckedChanged(RadioGroup group, int checkedId){
            RadioButton btn = (RadioButton)findViewById(checkedId);
            if(btn != null){
                  do_something();
            }
      }
  }

However, looks like this way doesn't work, the onCheckedChanged was never called. Anyone know what I should do? Thanks.

like image 888
Jie Liu Avatar asked Sep 08 '25 11:09

Jie Liu


2 Answers

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

itemtypeGroup.clearCheck();

then, same as usual add a listener:

mRadioGroup = (RadioGroup)findViewById(R.id.footer_radio);
            mRadioGroup.setOnCheckedChangeListener(this);
            mRadioGroup.clearCheck();

RadioButton btn = (RadioButton)view.findViewById(R.id.footer_btn_course);
btn.setChecked(true);
like image 79
Reprator Avatar answered Sep 10 '25 05:09

Reprator


I had the same problem..

and here is my approach:

 class Myclass extends Activity{
    protected void onCreate(Bundle savedInstanceState) {

    radiogroup = (RadioGroup) findViewById(R.id.radiogroupDecisionUncertain);
            radio1 = (RadioButton) findViewById(R.id.radiobuttonNo_U);
            radio2 = (RadioButton) findViewById(R.id.radiobuttonYes_U);
// declare the onCheckChangedListener
radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub

    if (checkedId == radio1.getId()) { //do something

                } else { // do other thing
                }

            }
        });

radiogroup.check(radio1.getId());


}
}

Notice that i set the checked radio button after registering the listener..

like image 32
Omar B. Avatar answered Sep 10 '25 05:09

Omar B.