Xamarin Android RadioButton and RadioGroup Introduction and Example


A radio button is a two-states button that can be either checked or unchecked.

These two states button are also normally generally called Compound buttons.

And indeed they derive from Android.Widget.CompoundButton, an abstract class that acts as an interface definition for a callback to be invoked when the checked state of a compound button changed.

So in a way a radiobutton share a similarity with CheckBox by deriving from the CompoundButton.

However, one big difference with CheckBox is that a RadioButton, unlike a CheckBox cannot be unchecked when it's already checked.

Say you have two radiobuttons: one maleRadioButton and the other femaleRadioButton. If you check male you expect female to be unchecked obviously.

However, if you click male twice, don't expect it to get unchecked. You have to move over to the female and then given that we have them in a RadioGroup, the female gets checked while the male gets unchecked.

You can check our video tutorial here:

RadioButton Definition

RadioButton is defined in the Android.Widget namespace:

namespace Android.Widget

That namespace belongs to the mono.Android assembly.

RadioButton is a concrete class that derives Android.Widget.CompoundButton:

public class RadioButton : Android.Widget.CompoundButton

On it's own RadioButton doesn't have any public method or public properties.

Instead it gets them via Inheritance from the CompoundButton class.

Important Properties and Methods

Here are some of the important properties of RadioButton

Property Type Description
public virtual bool Checked { set; get; } Property Get or Set checked state of the button.This actually defined in the CompoundButton class.
public virtual void Toggle() Method Changes the checked state of the view to the inverse of its current state. Also defined in the CompoundButton class.
public event System.EventHandler<CompoundButton.CheckedChangeEventArgs> CheckedChange Event Raised when the checked state of the RadioButton is detected.Also defined in the CompoundButton class.

Just the similar properties, events and methods that CheckBox gets.

RadioGroup

On their own, it would be difficult to juggle the states of many RadioButtons. This is because normally you expect only one radio button to be checked at any givem time.

This forces users to select only one item.

So there is a class called RadioGroup defined in the Android.Widget namespace that allows us easily work with many RadioButtons.

This is because when you add your RadioButtons inside a RadioGroup, then checking one radio button unchecks all the others.

RadioGroup derives from Android.Widget.LinearLayout:

public class RadioGroup : Android.Widget.LinearLayout

RadioGroup Important Properties,Methods and Events

Here are some important properties, methods and events for the RadioGroup class:

Property Type Description
public virtual int CheckedRadioButtonId { get; } Property Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
public virtual void Check(int id) Method Sets the selection to the radio button whose identifier is passed in parameter. Using -1 as the selection identifier clears the selection; such an operation is equivalent to invoking ClearCheck(). You pass the unique id of the radiobutton to select.
public virtual void ClearCheck() Method Clears the selection. When the selection is cleared, no radio button in this group is selected and CheckedRadioButtonId returns null.
public event System.EventHandler<RadioGroup.CheckedChangeEventArgs> CheckedChange Event Raised when the checked state of the radiobuttons in the group changes.

Example - Creating RadioButtons and RadioGroup Programmatically without XML

We'll now see an example. First we will programmatically instantiate several RadioButtons and one radiogroup, add the radiobutton in the radiogroup, and listen to checkChange events thus showing a Toast message with selected items it.

using System;
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Views;

namespace XamRadioButtonHello
{
    [Activity(Label = "XamRadioButtonHello", MainLauncher = true, Theme = "@android:style/android:Theme.Holo.Light.DarkActionBar", Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private RadioGroup myRadioGroup;
        private RadioButton america,europe,asia;

        private void createMultipleRadioButtons()
        {
            myRadioGroup = new RadioGroup(this);
            //instantiate  3 RadioButtons,
            america = new RadioButton(this)
            {
                Id = 1,
                Text = "America",
                Checked = true,
                LayoutParameters =
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent)
            };
            europe = new RadioButton(this)
            {
                Id = 2,
                Text = "Europe",
                LayoutParameters =
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent)
            };
            asia = new RadioButton(this)
            {
                Id = 3,
                Text = "Asia",
                LayoutParameters =
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent)
            };
            //add the RadioButtons to RadioGroup
            myRadioGroup.AddView(america);
            myRadioGroup.AddView(europe);
            myRadioGroup.AddView(asia);

        }
        /*
         * When Activity is Created.
         */
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            LinearLayout linearLayout = new LinearLayout(this)
            {
                LayoutParameters =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent),
                    Orientation = Orientation.Vertical
            };

            createMultipleRadioButtons();
            linearLayout.AddView(myRadioGroup);
            SetContentView(linearLayout);

            myRadioGroup.CheckedChange += myRadioGroup_CheckedChange;

        }
        /*
        * RadioButton CheckChange Event Handler
        */
        void myRadioGroup_CheckedChange(object sender, RadioGroup.CheckedChangeEventArgs e)
        {
            int checkedItem = myRadioGroup.CheckedRadioButtonId;
            Toast.MakeText(this,Convert.ToString(checkedItem),ToastLength.Short).Show();
        }

    }
}

Creating RadioGroup and RadioButtons with XML, then getting Text from Selected RadioButton

In this example we will see how to add the RadioGroup in our XML layout, add the RadioButtons to it, then in our C# code, when a radioButton is selected, show it's selected Text in a Toast message.

Main.axml

Here's our XML Layout code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="casual"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="RadioGroup and RadioButton"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />
    <RadioGroup
        android:id="@+id/myRadioGroup"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <RadioButton
            android:id="@+id/americaRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="America"
            android:padding="5dp" />
        <RadioButton
            android:id="@+id/europeRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Europe"
            android:padding="5dp" />
        <RadioButton
            android:id="@+id/asiaRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Asia"
            android:padding="5dp" />
        <RadioButton
            android:id="@+id/africaRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Africa"
            android:padding="5dp" />
    </RadioGroup>
</RelativeLayout>

MainActivity.cs

Here's our MainActivity

using System;
using Android.App;
using Android.Widget;
using Android.OS;

namespace Ms_RadioButtons
{
    [Activity(Label = "XamRadioButtonHello", MainLauncher = true, Theme = "@android:style/android:Theme.Holo.Light.DarkActionBar", Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private RadioGroup myRadioGroup;
        /*
         * Initialize RadioGroup and RadioButtons
         */
        private void initializeMultipleRadioButtons()
        {
            myRadioGroup = FindViewById<RadioGroup>(Resource.Id.myRadioGroup);

            myRadioGroup.CheckedChange += myRadioGroup_CheckedChange;
        }
        /*
       * RadioButton CheckChange Event Handler
       */
        void myRadioGroup_CheckedChange(object sender, RadioGroup.CheckedChangeEventArgs e)
        {
            int checkedItemId = myRadioGroup.CheckedRadioButtonId;
            RadioButton checkedRadioButton = FindViewById<RadioButton>(checkedItemId);
            Toast.MakeText(this, Convert.ToString(checkedRadioButton.Text), ToastLength.Short).Show();
        }
        /*
         * When Activity is Created.
         */
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            initializeMultipleRadioButtons();
        }
    }
}

RESULT

Xamarin Android RadioButton and RadioGroup

Xamarin Android RadioButton and RadioGroup

Good day.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post