android onCheckedChanged for radiogroup

前端 未结 6 1729
死守一世寂寞
死守一世寂寞 2021-01-07 16:39

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

6条回答
  •  半阙折子戏
    2021-01-07 17:35

    Even though @dannys answer is ok I would like to have the default value taken from the XML layout definition file rather then setting it in code.

    That's why I use this approach to:

    1. store the default value form the radio group
    2. clear all check's
    3. initialize the OnCheckedChangeListener
    4. check the default again (which was stored previously) which triggers the listener

    This could look like this in code with the first_radio_button as the default radio button:

    // call this in any init method
    _myRadioGroup    = _myViewContainingTheRadioGroup.findViewById(R.id.my_radio_group);
    int defaultValue = _myRadioGroup.getCheckedRadioButtonId();
    _myRadioGroup.clearCheck();
    _myRadioGroup.setOnCheckedChangeListener(_myRadioGroupCheckedChangeListener);
    _myRadioGroup.check(defaultValue);
    

    Place the OnCheckedChangeListener somewhere in your class:

    private RadioGroup.OnCheckedChangeListener _myRadioGroupCheckedChangeListener = new RadioGroup.OnCheckedChangeListener()
    {
      @Override
      public void onCheckedChanged(RadioGroup group, int checkedId)
      {
        switch(group.findViewById(checkedId).getId())
        {
          case R.id.first_radio_button:
            // do stuff
            break;
          case R.id.second_radio_button:
            // do stuff
            break;
          // ...
        }
      }
    };
    

    This is my radio group xml

      
    
        
    
        
    
        // ...
    
      
    

提交回复
热议问题