Last Updated:

Android Radio Button – Example

In this tutorial we will look at an example of using the radio button in Android. For those who have just started learning programming for Android, I advise you to first look at an example of working with a simple Button widget.

What is the radio button in Android

A widget is a button that can only take two positions (ON and OFF). Usually works with , which contains several radio buttons. When working with an active one widget, there can be only one widget. After pressing one radio button, the user can no longer turn off the same button by repeatedly pressing. This can only be done by pressing another button in .RadioButtonRadioButton RadioGroupRadioGroupRadioButtonRadioGroup

Attributes and properties of the RadioButton widget

  1. The attribute used in , specifies the location of the child element. This can be both horizontal and vertical position of the elements.android:orientationRadioGroup
  2. The method activates the radio button by the identifier passed to the parameter. check(id)
  3. Method - clears or cancels the selection of some switch. After applying this method, no button in will be selected and a subsequent call to the method returns . clearCheck()RadioButtonRadioGroupgetCheckedRadioButtonId()null
  4. The method returns the ID of the selected radio button in this group of radio buttons. If there are no child elements in , then -1 will be returned. getCheckedRadioButtonId()RadioGroupRadioButton
  5. The method applies a callback function that will be called if the switch in this . When you use the method, you must specify an instance of the . setOnCheckedChangeListener()RadioGroupsetOnCheckedChangeListener()RadioGroup.OnCheckedChangeListener

Example of using RadioButton in Android

 

To begin with, we need to create a simple android project. How to do this is described in this article. Below is the contents of the layout:activity_main.xml

Note, I used an attribute in the widget layout to immediately assign methods that will be called when you click on these buttons. These methods (onClear and onSubmit) are represented in the :android:onClickButtonMainActivity

Now let's run the application on the device or emulator and check the operability of our radio buttons:

 

As you can see, everything started normally and works perfectly. Follow the other tutorials in Programming for Android.