How to group RadioButton from different LinearLayouts?

marcoqf73 picture marcoqf73 · May 5, 2012 · Viewed 41.4k times · Source

I was wondering if is possible to group each single RadioButton in a unique RadioGroup maintaining the same structure. My structure look like this:

  • LinearLayout_main
    • LinearLayout_1
      • RadioButton1
    • LinearLayout_2
      • RadioButton2
    • LinearLayout_3
      • RadioButton3

As you can see, now each RadioButton is a child of different LinearLayout. I tried using the structure below, but it doesn't work:

  • Radiogroup
    • LinearLayout_main
      • LinearLayout_1
        • RadioButton1
      • LinearLayout_2
        • RadioButton2
      • LinearLayout_3
        • RadioButton3

Answer

SMBiggs picture SMBiggs · Nov 7, 2012

It seems that the good people at Google/Android assume that when you use RadioButtons, you don't need the flexibility that comes with every other aspect of the Android UI/layout system. To put it simply: they don't want you to nest layouts and radio buttons. Sigh.

So you gotta work around the problem. That means you must implement radio buttons on your own.

This really isn't too hard. In your onCreate(), set your RadioButtons with their own onClick() so that when they are activated, they setChecked(true) and do the opposite for the other buttons. For example:

class FooActivity {

    RadioButton m_one, m_two, m_three;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        m_one = (RadioButton) findViewById(R.id.first_radio_button);
        m_two = (RadioButton) findViewById(R.id.second_radio_button);
        m_three = (RadioButton) findViewById(R.id.third_radio_button);

        m_one.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_one.setChecked(true);
                m_two.setChecked(false);
                m_three.setChecked(false);
            }
        });

        m_two.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_one.setChecked(false);
                m_two.setChecked(true);
                m_three.setChecked(false);
            }
        });

        m_three.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_one.setChecked(false);
                m_two.setChecked(false);
                m_three.setChecked(true);
            }
        });

        ...     
    } // onCreate() 

}

Yeah, I know--way old-school. But it works. Good luck!