Saturday, 22 March 2014

grouping radio buttons in android

Through radio buttons user can select one option from a group Create each radio button option, use the RadioButton control in your layout. You have to place the multiple controls of RadioButton  and group then, by grouping them you make sure that only one redio button will select.
Place three radio button and group them it will look alike below;



XML code will be look alike for Radio button of android are below;
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
   
android:layout_width="fill_parent"
   
android:layout_height="wrap_content"
   
android:orientation="vertical">
   
<RadioButton android:id="@+id/radio_yes"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Yes"
       
android:onClick="onRadioButtonClicked"/>

   
<RadioButton android:id="@+id/radio_No"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="No"
       
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="@+id/radio_Maybe"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="May Be"
       
android:onClick="onRadioButtonClicked"/>

</RadioGroup>

The RadioGroup is subclass for  LinearLayout that has a vertical orientation by default.
Below code to handle the event of radio buttons
public void onRadioButtonClicked(View view) {

   
    boolean checked = ((RadioButton) view).isChecked();

    

    // Check which radio button was clicked

    switch(view.getId()) {

        case R.id.radio_yes:

            if (checked)

                // Selected Yes

            break;

        case R.id.radio_no:

            if (checked)

                // Selected No

            break;
        case R.id.radio_Maybe:

            if (checked)

                // Selected Maybe

            break;

    }

}


No comments:

Post a Comment