Tuesday, March 4, 2014

Android: Group RadioButtons

In this post I want to show, how to group RadioButtons under Android, such that always only one at a time can be activated. This is not hard, for this we simply create a RadioGroup in the current layout, to which we then add the RadioButtons. Then already at most one button can be active at a time, the selection of another one disables the current one. With the function Check() optionally a RadioButton can be chosen, which is activated on startup. For this the buttons have to have an Id, since the function Check() expects a such. In the following example we create a RadioGroup in a LinearLayout and add 3 RadioButtons to it. These we equip with Ids and activate the first one by default:

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

namespace RadioGroupExample
{
     [Activity (Label = "RadioGroupExample", MainLauncher = true)]
     public class MainActivity : Activity
     {

          protected override void OnCreate (Bundle bundle)
          {
               base.OnCreate (bundle);

               var LinearLayout = new LinearLayout (this);
               RadioGroup MyGroup = new RadioGroup (this);

               RadioButton RadioButton1 = new RadioButton (this);
               RadioButton1.Id = 1;
               RadioButton RadioButton2 = new RadioButton (this);
               RadioButton2.Id = 2;
               RadioButton RadioButton3 = new RadioButton (this);
               RadioButton3.Id = 3;

               MyGroup.AddView (RadioButton1);
               MyGroup.AddView (RadioButton2);
               MyGroup.AddView (RadioButton3);
               MyGroup.Check (1);

               LinearLayout.AddView (MyGroup);

               SetContentView (LinearLayout);
          }
     }
}

No comments:

Post a Comment