How to set only one RadioButton Can be selected at the time in RadioGroup
Asked Answered
S

8

33

I've created a radio button in radiogroup, but when I try running the apps all radio button can be selected all the time, and how to set only one radiobutton can be selected at one time?

I'm using Fragment

RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.RGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // find which radio button is selected
                if(checkedId == R.id.Abdominal) {
                    Toast.makeText(getActivity().getApplicationContext(), "choice: A",
                            Toast.LENGTH_SHORT).show();
                } else if(checkedId == R.id.Arm) {
                    Toast.makeText(getActivity().getApplicationContext(), "choice: B",
                            Toast.LENGTH_SHORT).show();
                } else if(checkedId == R.id.Back){
                    Toast.makeText(getActivity().getApplicationContext(), "choice: C",
                            Toast.LENGTH_SHORT).show();
                } else if(checkedId == R.id.Chest){
                    Toast.makeText(getActivity().getApplicationContext(), "choice: D",
                            Toast.LENGTH_SHORT).show();
                } else if(checkedId == R.id.Leg){
                    Toast.makeText(getActivity().getApplicationContext(), "choice: E",
                            Toast.LENGTH_SHORT).show();
                } else if(checkedId == R.id.Shoulder){
                    Toast.makeText(getActivity().getApplicationContext(), "choice: F",
                            Toast.LENGTH_SHORT).show();
                }
            }

        });

here my xml code for RG and RB

<RadioGroup
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/RGroup">

                    <TableRow android:weightSum="1">
                    <RadioButton
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Abdominal"
                        android:id="@+id/Abdominal"/>
                    <RadioButton
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Arm"
                        android:id="@+id/Arm"/>
                    <RadioButton
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Back"
                        android:id="@+id/Back" />
                        </TableRow>
                    <TableRow>
                        <RadioButton
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Chest"
                            android:id="@+id/Chest"/>
                        <RadioButton
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Leg"
                            android:id="@+id/Leg"/>
                        <RadioButton
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Shoulder"
                            android:id="@+id/Shoulder"/>
                    </TableRow>
                </RadioGroup>

EDITED 1 : Answer : If you dont want radio button can be selected in one time, so dont use Tablerow

Slowpoke answered 19/5, 2016 at 3:39 Comment(0)
P
32

It's not working because of TableRow inside RadioGroup. All RadioButtons are not grouped together because of TableRow between them.

RadioButton should be the direct child of RadioGroup, Otherwise grouping does not work.

Just change your code like this it will work :

        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/RGroup">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Abdominal"
                android:id="@+id/Abdominal"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Arm"
                android:id="@+id/Arm"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Back"
                android:id="@+id/Back" />                                        

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Chest"
                android:id="@+id/Chest"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Leg"
                android:id="@+id/Leg"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Shoulder"
                android:id="@+id/Shoulder"/>

        </RadioGroup>

Hope this helps. :)

Pulse answered 19/5, 2016 at 5:1 Comment(2)
Wow Thanks! this the answer, all button can selected one time bc of tablerow :) Thanks for helpSlowpoke
Btw, im using TableRow to make a radiobutton in 2 rows, so how to make it 2rwos without tablerow?Slowpoke
H
9

I have noticed that single selection does not work without setting id to radio buttons.

             <RadioGroup
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/expenseRadio"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:text="@string/expense" />

                <RadioButton
                    android:id="@+id/incomeRadio"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/income" />
            </RadioGroup>
Heavyladen answered 19/12, 2019 at 16:49 Comment(0)
S
7

I encountered the same issue and found where I was making mistakes, i'm describing it below:

  1. If you are using RadioButtons in RadioGroup, then RadioButtons should be Direct Child of RadioGroup.

  2. Check first condition, if it is correct then give id to RatioButton and run project, It will solve the problem automatically.

Saturable answered 25/6, 2019 at 7:24 Comment(0)
E
6
  <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:id="@+id/radioGroup">
        <RadioButton
            android:layout_width="0dp"
            android:layout_weight="50"
            android:layout_height="wrap_content"
            android:text="Debit"
            android:id="@+id/rDebit"
            android:checked="false"
             />

        <RadioButton
            android:layout_width="0dp"
            android:layout_weight="50"
            android:layout_height="wrap_content"
            android:text="Credit"
            android:id="@+id/rCredit"
            android:checked="false" />

    </RadioGroup>

And in java file

 RadioGroup radioGroup;



radioGroup = (RadioGroup) findViewById(R.id.radioGroup);

And when to do something

 if (radioGroup.getCheckedRadioButtonId() == R.id.rCredit)
{
// do something
}
Electroanalysis answered 19/5, 2016 at 3:42 Comment(1)
Following your code, but all radiobutton still can be selected in one time, im using fragment btw,Slowpoke
L
3

Simple way. onclick of radio button. do code as per below.

public void clearRadioChecked() {
    rdopa.setChecked(false);
    rdopb.setChecked(false);
    rdopc.setChecked(false);
    rdopd.setChecked(false);
}

if you wann select rdopa then on click of rdopa do as below.

clearRadioChecked()
rdopa.setChecked(true);
Lichtenfeld answered 19/5, 2016 at 5:9 Comment(2)
We better use CheckBoxes then.. You are not using RadioButton to manually check and uncheck it. The default behavior is one can be check at once other will be automatically uncheck.Pulse
@ janki gadhiya,if you have group of radiobutton and you wann reuse for many time then you need to implement above way.otherwise have single group of radio button then it works fine as per your concept automatically check/uncheck.Lichtenfeld
Z
3

You can use android:checkedButton attribute on RadioGroup, providing the id of the RadioButton you want to be checked initially and selecting another RadioButton will clear the previous selection.

<RadioGroup
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:checkedButton="@+id/rbNo"
     android:orientation="horizontal">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="50dp"
            android:text="Yes" />

        <RadioButton
            android:id="@+id/rbNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="No" />
</RadioGroup>
Zirconium answered 31/1, 2019 at 19:23 Comment(0)
V
3

We can use any layout like LinearLayout, RelativeLayout, ConstraintLayout or GridLayout as RadioGroup using the following method in Kotlin.

For the following example I used ConstraintLayout to get fixed width and height for RadioButton.

layout.xml

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/radioGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/rbYellow"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="@dimen/space_2x"
        android:layout_marginEnd="@dimen/space"
        android:gravity="center"
        android:text="Yellow"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toStartOf="@+id/rbOrange"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RadioButton
        android:id="@+id/rbOrange"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="@dimen/space"
        android:layout_marginEnd="@dimen/space"
        android:gravity="center"
        android:text="Orange"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="@id/rbYellow"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toStartOf="@+id/rbRed"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/rbYellow"
        app:layout_constraintTop_toTopOf="@id/rbYellow" />

    <RadioButton
        android:id="@+id/rbRed"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="@dimen/space"
        android:layout_marginEnd="@dimen/space"
        android:gravity="center"
        android:text="Red"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="@id/rbYellow"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toStartOf="@+id/rbGreen"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/rbOrange"
        app:layout_constraintTop_toTopOf="@id/rbYellow" />

    <RadioButton
        android:id="@+id/rbGreen"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="@dimen/space"
        android:layout_marginEnd="@dimen/space_2x"
        android:gravity="center"
        android:text="Green"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="@id/rbYellow"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/rbRed"
        app:layout_constraintTop_toTopOf="@id/rbYellow" />
</androidx.constraintlayout.widget.ConstraintLayout>

Kotlin code

radioGroup.children.forEach { aBtn ->
    (aBtn as RadioButton).setOnCheckedChangeListener { button, isChecked ->
        if(isChecked) {
            radioGroup.children.forEach { bBtn ->
                if(bBtn.id != button.id) {
                    (bBtn as RadioButton).isChecked = false
                }
            }
        }
    }
}
Vino answered 12/4, 2022 at 10:6 Comment(0)
K
2

You can create your own RadioGroup, that is able to find all RadioButtons that are nested in your group regardless of direct child or not. Below the code of my NestedRadioGroup. Using this instead of your RadioGroup in your xml file should do the trick.

public class NestedRadioGroup extends LinearLayout {
    private SparseArray<RadioButton> radioButtons;
    private int checkedId;

    public NestedRadioGroup(Context context) {
        this(context, null);
    }

    public NestedRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        radioButtons = new SparseArray<>();
        checkedId = -1;
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        findRadioButtons(child);
    }

    private void findRadioButtons(View child) {
        if (child instanceof RadioButton) {
            RadioButton newButton = (RadioButton) child;
            newButton.setId(radioButtons.size());
            newButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    if (checkedId != -1) {
                        radioButtons.get(checkedId).setChecked(false);
                    }
                    radioButtons.get(buttonView.getId()).setChecked(true);
                    checkedId = buttonView.getId();
                }
            });
            radioButtons.put(newButton.getId(), newButton);
        } else if (child instanceof ViewGroup) {
            ViewGroup group = (ViewGroup) child;

            for (int i = 0; i < group.getChildCount(); i++) {
                this.findRadioButtons(group.getChildAt(i));
            }
        }
    }
}

Any ideas to make the code cleaner?

I hope it works out for you :)

Kinch answered 15/6, 2019 at 7:15 Comment(2)
Exactly what i looking for, Thank you son much :)Cathee
This should be the accepted answer by far. But be careful with complex layouts, mostly ConstraintLayout inside your XML. Declaring fixed sizes solved it in my case.Anechoic

© 2022 - 2024 — McMap. All rights reserved.