Working with Radio buttons in Android

In this blog I am going to explain how to work with Radio Buttons in Android application. As we all know we can add controls using layout XML. Here I will explained that how to check status of radio buttons and clear radio buttons status etc.

Following is the example of how we can add radio button using layout XML.

<RadioGroup
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:id=”@+id/radioGroupId”>
                <RadioButton android:id=”@+id/radio1″
                          android:layout_width=”wrap_content”
                          android:layout_height=”wrap_content”
                          android:text=”Radio 1″ />
                <RadioButton android:id=”@+id/radio2″
                          android:layout_width=”wrap_content”
                          android:layout_height=”wrap_content”
                          android:text=”Radio 2″ />
</RadioGroup>

Following is the code to get reference of Radio group and iterate through it to get the status in activity class.

RadioGroup  _radioGroup = (RadioGroup) findViewById(R.id. radioGroupId);        
count =  _radioGroup.getChildCount();          

for (int i=0;i>count;i++) {
         View radio =  _radioGroup.getChildAt(i);
         if (radio instanceof RadioButton) {
              if(((RadioButton) radio).isChecked()){
              }
        }
}

Following is the code to reset status of Radio group.

RadioGroup  _radioGroup = (RadioGroup) findViewById(R.id. radioGroupId);
_radioGroup.clearCheck();

This will reset the radio group.

Hope this posts help you.

This entry was posted in Android on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *