Set Radio Button To Android Layout

Radio button is the option where we can select one option from multiple, in android its little bit .

We need to take a radio group inside radio group declare all the radio option with one method which will be called at radio selection type and assign the value to a variable.


 <RadioGroup
        android:id="@+id/typeRadio  >

        <RadioButton
            android:id="@+id/radio_male"
            android:text="Male"
            android:onClick="onRadioButtonClicked"/>

        <RadioButton
            android:id="@+id/radio_female"
            android:text="Female"
            android:onClick="onRadioButtonClicked"/>

    </RadioGroup>

After making layout set the  variable in the activity class and asign its value through the onclick method.

private String gender;

protected void onCreate(Bundle savedInstanceState) {

RadioGroup rg = (RadioGroup) findViewById(R.id.ammountTypeRadio);

}

Here Radio button on-click method will respond on each time radio will selected and will be assign to variable.

public void onRadioButtonClicked(View view){

        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.radio_male:
                if (checked)
                    gender = "male";
                    break;
            case R.id.radio_female:
                if (checked)
                    gender="female";
                    break;
        }
    }





Post a Comment

Previous Post Next Post