info@androidpaper.co.in

How to Use Radio Button In Android Studio

In this tutorial, we'll walk you through the entire process of working with Radio Buttons in Android. You'll learn how to incorporate Radio Buttons into your app's UI, allowing users to choose a single option from a group of choices that are mutually exclusive. We'll start by introducing Radio Buttons and their significance in creating dynamic user interfaces. You'll gain a clear understanding of their purpose and how they contribute to a seamless user experience.

Radio Button
The RadioButton component is typically used in conjunction with the RadioGroup component. When multiple radio buttons are placed inside a RadioGroup, selecting one radio button automatically deselects all others. The RadioGroup component acts as a container for radio buttons, ensuring that only one option can be selected at a time. This behavior is achieved by automatically unchecking any other radio buttons within the same group when one is checked.

Example:
main_activity.xml

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

        <RadioButton
            android:id="@+id/rd1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:text="RadioOne" />

        <RadioButton
            android:id="@+id/rd2"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:text="RadioTwo" />

        <RadioButton
            android:id="@+id/rd3"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:text="RadioThr" />

        <RadioButton
            android:id="@+id/rd4"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:text="RadioFr" />
    </RadioGroup>


    <Button
        android:id="@+id/btn_radio"
        android:layout_width="120dp"
        android:layout_height="80dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Submit" />

Now, lets code for the Radio Button
MainActivity.java

RadioGroup rdGroup;
RadioButton rd1,rd2,rd3,rd4;
RadioButton seltedRedioButon;

In onCreate method

 rdGroup = findViewById(R.id.rdGroup);
 btn_radio = findViewById(R.id.btn_radio);
 btn_radio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                seltedRedioButon =  findViewById(rdGroup.getCheckedRadioButtonId());
                String seledtedButnvalue= seltedRedioButon.getText().toString();
                Toast.makeText(TexttViewActivity.this, seledtedButnvalue, Toast.LENGTH_SHORT).show();
            }
        });

Let's Run the App