Friday, January 20, 2012

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.




No comments:

Post a Comment