How to group RadioButton from different LinearLayouts?

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!

Leave a Comment