RadioGroup with two columns which have ten RadioButtons

后端 未结 12 1997
难免孤独
难免孤独 2020-11-27 07:16

I have a RadioGroup and I want to align buttons next to each other in two columns and five rows and I am unable to achieve it. Things I have tried:

12条回答
  •  暖寄归人
    2020-11-27 07:34

    A couple of the other answers work fine, but are more complicated than required for simpler cases. If you just want multiple RadioGroups to act as one and can handle all of the decision making at the time of the click, then you can do this:

    In your layout XML, add the same click handler to all of the RadioButtons that you want combined:

    android:onClick="handleCombinedClick"
    

    Then, make your click handler look something like this:

    public void handleCombinedClick(View view) {
        // Clear any checks from both groups:
        rg1.clearCheck();
        rg2.clearCheck();
    
        // Manually set the check in the newly clicked radio button:
        ((RadioButton) view).setChecked(true);
    
        // Perform any action desired for the new selection:
        switch (view.getId()) {
            case R.id.radio_button_1:
                // do something
                break;
    
            case R.id.radio_button_2:
                // do something
                break;
    
            ...
        }
    }
    

    This has the added benefit of having all of your choices handled in the same spot. And if you want to extend this to 3 or more RadioGroups, then you just need to add an additional rgX.clearCheck(); line for each added group.

提交回复
热议问题